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.
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.
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.
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.
getList("instance").
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 => }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With