Last Updated: February 25, 2016
· oskarwickstrom

Aliases in Scala Pattern Matching

I found this simple but very useful Scala feature just the other day.

If we have a Person</code> class like this...

case class Person(firstName : String, lastName : String)

... and we want to use pattern matching to ensure an object is a Person</code> with lastName</code> "Jones" before send it to someFunction</code>, we could do something like this:

someObject match {
  case Person(fn, "Jones") => 
    someFunction(Person(fn, "Jones"))

Not very nice, right? As the whole Person</code> object is of interest, we might do something like this instead...

case p : Person => someFunction(p)

But now we don't have any pattern matching left, the person could have any last name! So, how do we bind the Person</code> object and keep our last name check? By using an alias!

case (p @ Person(_, "Jones")) => someFunction(p)

The Person object is now bound to the val p</code> and can be passed on to someFunction</code>.

Say Thanks

2 Responses
Add your response

E9e226a700a96f71d98a4616ab7bc465 normal

Do aliases work with no case classes? If yes which unapply unapplySeq is needed to implement?

over 1 year ago ·
Nektgllk normal

Yup, non-case classes can be used in an alias syntax but, as you've suggested, it's required to provide an unapply method to make things work. See PatternMatching.scala for an example.

over 1 year ago ·