A few months ago, Joshua D. Suereth gave a very nice technical talk at Devoxx 2013, titled “How to wield Scala in the trenches“, which was full of functional programming & Scala gems. The last slides of his presentation were dedicated to a very powerful style of using extractors and pattern matching. I liked his example so much that I wanted to understand it better and note it down in my blog so that I can apply it in many similar cases.

The basic motivation comes from the following question. Assume you have a List of objects, e.g. People, who can have more than one residence; and you want to select the ones based on a condition, e.g. the ones living in Istanbul. There are of course different ways to traverse the list and filter the ones you are looking for:

Wouldn’t it be nice to do pattern matching over that List in an almost natural language-like manner, such as:

and get a result such as

List(Ergin, Ahmet)

Thanks to extractors, it is possible to achieve the intended effect by defining LivesIn and Istanbul like

You can find a self-contained example, PatternPower.scala which you can compile and run at the end of this blog entry. This technique, presented by Suereth at Devoxx 2013, seems simple and fundamental once you understand it, like many advanced programming idioms. It also shows that with proper abstractions and usage of constructs, Scala proves itself again in the field of readable code. For those who want to learn about extractors used in pattern matching in Scala, I suggest The Neophyte’s Guide to Scala Part 1: Extractors.

PatternPower.scala: