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>.
Written by Oskar Wickström
Related protips
2 Responses
Do aliases work with no case classes? If yes which unapply unapplySeq is needed to implement?
@twitbrainless:
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.