How to pattern match multiple values in Scala?

François Beausoleil picture François Beausoleil · Aug 26, 2011 · Viewed 44.6k times · Source

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.

Answer

axel22 picture axel22 · Aug 26, 2011

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 =>
}