Switch in Scala (pattern matching)

Scala has a powerful “switch”, usually called pattern matching, with many options I’d like to explore here. A simple switch looks like this:

a match {
  case 1 => "One"
  case 2 => "Two"
  case _ => "Whatever"
}

In this case we have cases with 1 and 2, and if something else is matched then we return “Whatever”. But this is really simple, let’s make it more complex matching with types too.

a match {
  case i: Int => "Integer!"
  case s: String => "String: " + s
  case _ => "Whatever"
}

The above piece of code would look like this in Java:

if (a instanceOf Integer) return "Integer!";
if (a instanceOf String) return "String: " + s;
return "Whatever";

Now if a is a string we return “String”, if it’s an integer we return “Integer!” and if it’s something else we return “Whatever”.

We can also match against case classes. Imagine we have a case class with an integer and a string, Element.

case class Element(weight: Int, name: String)

In that case we can make a more complete match:

Element(85, "Fruit") match {
  case Element(_, "Fruit") => "Fruit is coming"
  case Element(80, _) => "80 kg!"
  case Element(80, "Fruit") => "80 kg of Fruit"
  case _ => "Whatever"
}

Apart from all the options described here we can add a boolean before the =>

Element(85, "Fruit") match {
  case Element(weight, "Fruit") if weight > 50 => "More than 50kg of fruit are coming"
  case Element(80, _) => "80 kg!"
  case _ => "Whatever"
}

The nice thing about pattern matching is that you can use exactly the same structures in closures or catch blocks.