How do I pattern match arrays in Scala?

Scala

Scala Problem Overview


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?

Scala Solutions


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

Solution 2 - Scala

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

Solution 3 - Scala

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

Solution 4 - Scala

case statement doesn't work like that. That should be:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeltanovemberView Question on Stackoverflow
Solution 1 - ScalaRuediger KellerView Answer on Stackoverflow
Solution 2 - ScalasynapseView Answer on Stackoverflow
Solution 3 - ScalaparadigmaticView Answer on Stackoverflow
Solution 4 - ScalamissingfaktorView Answer on Stackoverflow