Skip to content

Instantly share code, notes, and snippets.

@emres
Created January 4, 2014 19:14
Show Gist options
  • Save emres/8259412 to your computer and use it in GitHub Desktop.
Save emres/8259412 to your computer and use it in GitHub Desktop.
A concrete demonstration of the technique presented by Joshua Suereth in Devoxx 2013.
case class Person(name: String, residence: Seq[Residence])
case class Residence(city: String, country: String)
object LivesIn {
def unapply(p: Person): Option[Seq[String]] =
Some(
for(r <- p.residence)
yield r.city
)
}
class StringSeqContains(value: String) {
def unapply(in: Seq[String]): Boolean =
in contains value
}
object PatternPower extends App {
val people =
List(Person("Emre", List(Residence("Antwerp", "BE"))),
Person("Berk", List(Residence("Antwerp", "BE"))),
Person("Ergin", List(Residence("Istanbul", "TR"),
Residence("Ankara", "TR"))),
Person("Ahmet", List(Residence("Istanbul", "TR"))))
val Istanbul = new StringSeqContains("Istanbul")
val peopleInIstanbul = people collect {
case person @ LivesIn(Istanbul()) => person.name
}
println(peopleInIstanbul)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment