Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match multiple values in Scala?

Let's say I want to handle multiple return values from a remote service using the same code. I don't know how to express this in Scala:

code match {   case "1" => // Whatever   case "2" => // Same whatever   case "3" => // Ah, something different } 

I know I can use Extract Method and call that, but there's still repetition in the call. If I were using Ruby, I'd write it like this:

case code when "1", "2"   # Whatever when "3"   # Ah, something different end 

Note that I simplified the example, thus I don't want to pattern match on regular expressions or some such. The match values are actually complex values.

like image 344
François Beausoleil Avatar asked Aug 26 '11 19:08

François Beausoleil


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 does Scala pattern matching work?

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.

What is the default option in a match case in Scala?

getList("instance").


1 Answers

You can do:

code match {   case "1" | "2" => // whatever   case "3" => } 

Note that you cannot bind parts of the pattern to names - you can't do this currently:

code match {   case Left(x) | Right(x) =>   case null => } 
like image 117
axel22 Avatar answered Oct 16 '22 09:10

axel22