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?

Answers


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

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. That should be:

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

Need Your Help

How to properly overload the << operator for an ostream?

c++ namespaces operator-overloading iostream ostream

I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my com...

Toggle the glyphicon with bootstrap collapse

javascript jquery html twitter-bootstrap glyphicons

I have glyphicon-chevron-down when div is in collapsed state,i want to replace it with glyphicon-chevron-up when the div is in collapse in state.I have many of these collapsible divs in my project....