Created
July 8, 2012 20:34
-
-
Save owickstrom/3072696 to your computer and use it in GitHub Desktop.
Aliases in Scala pattern matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If we have a Person class like this... | |
case class Person(firstName : String, lastName : String) | |
// ... and we want to use pattern matching to ensure | |
// an object is a Person with lastName "Jones" before | |
// send it to someFunction, we could do something like | |
// this: | |
someObject match { | |
case Person(fn, "Jones") => someFunction(Person(fn, "Jones")) | |
} | |
// Not very nice, right? | |
// As the whole Person 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 object and keep our | |
// last name check? By using an alias! | |
case (p @ Person(_, "Jones")) => someFunction(p) | |
// I found this easy but incredibly useful feature just the | |
// other day. The type system in Scala never ceases to amaze me! :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 for use of parentheses
they are actually redundant here
( at least for v2.13.0)
but useful for alternatives: