我的方法定义如下
def processLine(tokens: Array[String]) = tokens match { // ...
假设我想知道第二个字符串是否为空
case "" == tokens(1) => println("empty")
不编译。我该怎么做呢?
发布于 2011-07-11 16:38:17
如果要对数组进行模式匹配以确定第二个元素是否为空字符串,可以执行以下操作:
def processLine(tokens: Array[String]) = tokens match {
case Array(_, "", _*) => "second is empty"
case _ => "default"
}
_*
可以绑定到任意数量的元素,包括没有元素。这与下面的列表匹配类似,后者可能更为人所知:
def processLine(tokens: List[String]) = tokens match {
case _ :: "" :: _ => "second is empty"
case _ => "default"
}
发布于 2014-01-30 07:58:07
更酷的是,您可以为_*
匹配的内容使用别名,如下所示
val lines: List[String] = List("Alice Bob Carol", "Bob Carol", "Carol Diane Alice")
lines foreach { line =>
line split "\\s+" match {
case Array(userName, friends@_*) => { /* Process user and his friends */ }
}
}
发布于 2011-07-11 15:58:37
case
语句不是这样工作的。这应该是:
case _ if "" == tokens(1) => println("empty")
https://stackoverflow.com/questions/6647166
复制相似问题