How do I match match arrays in Scala?

The definition of my method is as follows

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

Suppose I want to know if the second row is free

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

Not compiled. How should I do it?

+55
scala
Jul 11 2018-11-11T00:
source share
4 answers

If you want to map a pattern in an array to determine if the second element is an empty string, you can do the following:

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

_* associated with any number of elements, including none. This is similar to the following list match, which is probably better known:

 def processLine(tokens: List[String]) = tokens match { case _ :: "" :: _ => "second is empty" case _ => "default" } 
+94
Jul 11 2018-11-11T00:
source share

Matching patterns might not be the right choice for your example. You can simply do:

 if( tokens(1) == "" ) { println("empty") } 

Pattern matching is more suitable for situations such as:

 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 is any token that is an empty string, you can also try:

 if( tokens.exists( _ == "" ) ) { println("Found empty token") } 
+7
Jul 11 '11 at 8:10
source share
Operator

case does not work. It should be:

 case _ if "" == tokens(1) => println("empty") 
+3
Jul 11 2018-11-11T00:
source share

What is especially cool is that you can use an alias for 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 */ } } } 
+3
Jan 29 '14 at 23:58
source share



All Articles