I am trying to reproduce an example of a powerful template that Joshua Suereth presented in his 2013 Devoxx interview entitled "How to Own Scala in the Trenches." Unfortunately, I cannot achieve what he described, and I cannot understand what is wrong. Can someone give me a hint about what I am missing? (My version of Scala is 2.10.3)
Please check out the code below:
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 =
Seq(Person("Emre", Seq(Residence("Antwerp", "BE"))),
Person("Ergin", Seq(Residence("Istanbul", "TR"))))
val Istanbul = new StringSeqContains("Istanbul")
//
println(
people collect {
case person @ LivesIn(Istanbul) => person
}
)
//
println(
people collect {
case person @ LivesIn(cities) if cities.contains("Istanbul") => person
}
)
//
println(
people collect {
case person @ Person(_, res) if res.contains(Residence("Istanbul", "TR")) => person
}
)
}
When I compile and run it, I get:
List()
List(Person(Ergin,List(Residence(Istanbul,TR))))
List(Person(Ergin,List(Residence(Istanbul,TR))))
As indicated in the source code, I do not understand why the first template does not give the same result as the other two templates. Any ideas why?
source
share