如何在 Scala 中使用模式匹配数组?

我的方法定义如下所示

def processLine(tokens: Array[String]) = tokens match { // ...

假设我想知道第二个字符串是否为空

case "" == tokens(1) => println("empty")

没有编译。我该怎么做呢?

41678 次浏览

case语句不是这样工作的,应该是:

case _ if "" == tokens(1) => println("empty")

模式匹配可能不是正确的选择,你可以简单地这样做:

if( tokens(1) == "" ) {
println("empty")
}

模式匹配更适用于以下情况:

for( t <- tokens ) t match {
case "" => println( "Empty" )
case s => println( "Value: " + s )
}

它为每个标记打印一些内容。

编辑: 如果您想检查是否存在任何空字符串标记,也可以尝试:

if( tokens.exists( _ == "" ) ) {
println("Found empty token")
}

如果希望在数组上进行模式匹配以确定第二个元素是否为空字符串,可以执行以下操作:

def processLine(tokens: Array[String]) = tokens match {
case Array(_, "", _*) => "second is empty"
case _ => "default"
}

_*绑定到任意数量的元素,其中不包括任何元素。这类似于 List 上的以下匹配,这个匹配可能更为人所知:

def processLine(tokens: List[String]) = tokens match {
case _ :: "" :: _ => "second is empty"
case _ => "default"
}

特别酷的是,你可以使用一个别名的东西与 _*匹配的东西

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 */ }
}
}