Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pattern match arrays in Scala?

Tags:

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?

like image 364
deltanovember Avatar asked Jul 11 '11 07:07

deltanovember


People also ask

Does Scala have pattern matching?

Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.

How do you match a pattern in Scala?

A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.

What is the use of Scala pattern matching?

Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.

What is case class and pattern matching in Scala?

It is defined in Scala's root class Any and therefore is available for all objects. The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.


1 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" } 
like image 171
Ruediger Keller Avatar answered Sep 30 '22 08:09

Ruediger Keller