我如何在Scala模式匹配数组?

我的方法定义如下所示

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

假设我想知道第二个string是否为空

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

不编译。 我怎么去做这个?

如果要对数组进行模式匹配以确定第二个元素是否为空string,则可以执行以下操作:

 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" } 

模式匹配可能不是您的示例的正确select。 你可以简单地做:

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

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

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

打印每个令牌的东西。

编辑:如果你想检查是否存在任何一个空string的标记,你也可以尝试:

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

case陈述不起作用。 这应该是:

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

什么是额外的酷,是你可以使用类似_*的东西匹配的东西的别名

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