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:
def processLine(tokens: List[String]) = tokens match {
case _ :: "" :: _ => "second is empty"
case _ => "default"
}
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 */ }
}
}