简体   繁体   English

如何在 Scala 中模式匹配 arrays?

[英]How do I pattern match arrays in Scala?

My method definition looks as follows我的方法定义如下

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

Suppose I wish to know whether the second string is blank假设我想知道第二个字符串是否为空

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

Does not compile.不编译。 How do I go about doing this?我该怎么做呢?

If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following:如果要对数组进行模式匹配以确定第二个元素是否为空字符串,可以执行以下操作:

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

The _* binds to any number of elements including none. _*绑定到任意数量的元素,包括没有。 This is similar to the following match on Lists, which is probably better known:这类似于 Lists 上的以下匹配,这可能更为人所知:

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

Pattern matching may not be the right choice for your example.模式匹配可能不是您的示例的正确选择。 You can simply do:你可以简单地做:

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

Pattern matching is more approriate for cases like:模式匹配更适合以下情况:

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

which print something for each token.它为每个令牌打印一些东西。

Edit: if you want to check if there exist any token which is an empty string, you can also try:编辑:如果您想检查是否存在任何空字符串的令牌,您也可以尝试:

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

What is extra cool is that you can use an alias for the stuff matched by _* with something like更酷的是,您可以为_*匹配的内容使用别名,例如

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

case statement doesn't work like that. case语句不能那样工作。 That should be:那应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM