So I learned something from the book:
//Binding
class Role
case object Manager extends Role
case object Developer extends Role
case class Person(name: String, age: Int, role: Role)
val alice = new Person("Alice", 25, Developer)
val bob = new Person("Bob", 32, Manager)
val charlie = new Person("Charlie", 32, Developer)
for (item <- Map(1 -> alice, 2 -> bob, 3 -> charlie)) {
item match {
case(id, p @ Person(_, _, Manager)) => println(p+ " ist überbezahlt")
case(id, p @ Person(_, _, _)) => println(p+ " ist unterbezahlt")
}
}
/*Das in der case-Klausel eingebette p @ PErson(...) prüft die Übereinstimmung mit einer Person innerhalb
eines umschließenden Tupels.
Gleichzeitig binden wir die Person an eine Variable p, die wir für folgende Ausgaben verwenden. */
It’s german, sorry for that.
It is well explained and all… but I was experimenting a bit. I changed 2 lines as follows:
case(p @ Person(_, _, Manager)) => println(p+ " ist überbezahlt")
case(p @ Person(_, _, _)) => println(p+ " ist unterbezahlt")
I get the error message in the title.
The book doesn’t exlain what’s the deal with the id is. It is not a reserved word. Maybe it is obvious, but I am too dense to comprehend this, why the id is necessary.
But then I tried the following:
case(abc, p @ Person(_, , Manager)) => println(p+ " ist überbezahlt")
case(xzy, p @ Person(, _, _)) => println(p+ " ist unterbezahlt")
It works!
I am now completely puzzled; the “id” seems to be a filler (so it is formated in the right way?).
Anyhow, I would much appreciate if someone could explain this mind and matter to me
EDIT: Some underscores are missing in the last example