Created
January 4, 2014 19:14
-
-
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.
This file contains hidden or 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
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