Skip to content

Instantly share code, notes, and snippets.

@owickstrom
Created July 8, 2012 20:34
Show Gist options
  • Save owickstrom/3072696 to your computer and use it in GitHub Desktop.
Save owickstrom/3072696 to your computer and use it in GitHub Desktop.
Aliases in Scala pattern matching
// 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! :)
@GlulkAlex
Copy link

+1 for use of parentheses
they are actually redundant here
( at least for v2.13.0)
but useful for alternatives:

scala> Iterator("{", "a:1","},","{", "b:3", "},", "{", "c:42", "}").collect{ case w @ (s"a:$_" | s"b:$_") => w }.toList
res32: List[String] = List(a:1, b:3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment