Why doesn't this pattern combination work in Scala?

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")

  // #1 does not work as expected, WHY?
  println(
    people collect {
      case person @ LivesIn(Istanbul) => person
    }
  )

  // #2 works as expected
  println(
    people collect {
      case person @ LivesIn(cities) if cities.contains("Istanbul") => person
    }
  )

  // #3 works as expected
  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?

+4
source share
2 answers

Googling , () ( Scala 1: ).

, :

people collect {
  case person @ LivesIn(Istanbul()) => person
}

- , , List():

people collect {
  case person @ LivesIn(Istanbul) => person
}

- (, ), , / ( ; -)

+1

LivesIn Seq.

, :

println(
  people collect {
    case person @ LivesIn(List("Istanbul")) => person
  }
)
+6

All Articles