How do I pattern match arrays in Scala?

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

Leave a Comment