How do I pattern match arrays in Scala?

前端 未结 4 761
感动是毒
感动是毒 2020-12-01 05:46

My method definition looks as follows

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

Suppose I wish to know whether the sec

4条回答
  •  天命终不由人
    2020-12-01 06:34

    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:

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

提交回复
热议问题