Scala Pattern Matching explained

I am currently reading Programming in Scala. For a programmer coming from an imperative world there many new concepts to learn. One of them is Pattern Matching. There are already lots of articles about it, but explaining something is still one of the best ways to learn. Here are the first 4 levels of understanding Pattern Matching.

Level 1 – Pattern Matching as simple switch/case replacement

Pattern Matching can simply be used to replace Java switch/case statements. This is called constant pattern and looks like this:

  def constantMatch(value:Any) = {
    value match {
      case "Hello" => "You said hello!"
      case 1 => "Oh, thats a 1!"
      case _ => "Don't know what you want!"
    }
  }

ConstantMatch is a function that takes a parameter of type Any. Any is the Scala pendant to java.lang.Object. This value is now matched against several constants. The first case is a String the second an Int and the last case is a wildcard for any other value.
There are a few differences to Java. First, there is no “fall through”. If a pattern has been matched its value will be returned. Thats the part after the => operator. This can be a full code block. The example above just shows the short version. The second difference is if no pattern matches Scala will throw a MatchError Exception. This is why the wildcard pattern is needed as the last line. This is more or less the same as the default clause of Java.

Level 2 – Introducing Variable patterns

Now level 1 was already more powerful than Java switch/case. But there are some more levels to go. The next step is introducing variable pattern. Here is an example:

 def variableMatch(value:Any) = {
    value match {
      case 1 =>"Oh, thats a 1!"
      case x =>"And thats a"+x+"!";
    }
  }

Instead of validating every possibly value the value itself is put into a variable. This variable can then be processed in the result block. You might recognize that there is no wildcard case(case _ => …). This is not necessary as the variable pattern will match any possible value. A wildcard would not even be possible. The compiler will complain that it is unreachable code.

Level 3 – Type Patterns

Type patterns allow to calculate the result based on the type of the value. Instead of using instanceof in Java or isInstanceOf in Scala this can just be done in a case statement. Let’s assume we have a class hierarchy used to calculate the financial value of different types of property.

abstract class Property {
  val value: BigDecimal
}

case class House(address: Address, override val value:BigDecimal) extends Property
case class Car(horsepower: Int, override val value:BigDecimal) extends Property
case class Horse(Age:Int, override val value:BigDecimal) extends Property
case class Address(street: String, city: String)

Ignore the case keyword for the moment. This is level 4. For all Java people, this code can be put in one file, although it is not recommended practice. I just do it here for simplicity. Property is the abstract base class. It defines a field value as all property needs to have a value. House, Car and Horse inherit from Property and add additional information. Address will be used in a later example.

For a special calculation the value will be applied based on the type of property. Houses will be applied with 80% of their value, Horses with 50% and the value of Cars will not be applied at all. Using Pattern Matching this looks like this:

  def applyPropertyValue(property:Property):BigDecimal = property match {
    case house:House => house.value * 0.8
    case horse:Horse => horse.value * 0.5
    case car:Car => 0
    case _ => property.value
  }

Without any instanceof or casting the value has been calculated based on the type of property. Here is a wildcard pattern used in the last line again. If there is another type of property the full value will be applied.

Level 4 – Constructor patterns and Case Classes
The last example already used case classes even if it would have worked with normal classes too. Case classes have some special characteristics.

  • There is a special factory method that allows the class to be instantiated without the new keyword. Car(150,20000) creates a Car object with 150 horsepower and a value of 20.000.
  • All parameters in the constructor are automatically defined as val. So they are fields and can be accessed from other objects.
  • The compiler generates meaningful implementations of equals, hashcode and toString.
  • And of course they can be used in constructor patterns.

In our example we need some very special cases to calculate the value. If a house is in Berlin 90% instead of 80% of the value can be applied. Cars with a horsepower of more than 150 can be applied with 50% of their value instead of 0. Our function now gets two more lines:

  def applyPropertyValue(property:Property):BigDecimal = property match {
    case House(Address(_,"Berlin"),value) => value * 0.9 //Deep match
    case Car(horsepower, value) if horsepower > 150 => value * 0.5 //Pattern Guard
    case house:House => house.value * 0.8
    case horse:Horse => horse.value * 0.5
    case car:Car => 0
    case _ => property.value
  }

The more special a case is the earlier it has to be validated. If the general case for Car would be matched first, the more specialized pattern would never be validated. In simple cases the Scala compiler complains about the code being unreachable.
The two new lines use the constructor pattern, that is only possible for case classes. But both also demonstrate other features of Pattern Matching. The House pattern shows a nested pattern. The important condition is in class Address, which is nested inside House. This kind of deep matches can save a lot of code. Imagine how many if statements, casts and instanceofs this needs in Java. The Car example shows another syntax for pattern matching. It is called Pattern Guards. An additional if after the pattern allows to validate conditions, before the pattern code will be excecuted.

Level 5 and above
This is still not all that can be learned about Pattern Matching. The story goes on with sequence patterns, sealed classes, partial functions and much more. But by now you should be able to understand most Pattern Matching statements that can be found in Scala. For more details I can only recommend reading Programming in Scala. It contains a lot of fun stuff like that.

Be Sociable, Share!
  1. Ajith says:

    Very nicely explained.

  1. There are no trackbacks for this post yet.

Leave a Reply