I am trying to understand the scala unapply method.
Below is my understanding. Say if I have a Person object:
class Person(val fname: String, val lname: String)
object Person{
def unapply(x: Person) : Option[(String, String)] =
Some(x.fname,x.lname)
}
new Person("Magic", "Mike") match {
case Person(x, y) => s"Last Name is ${y}"
case _ => "Unknown"
}
This i presume the case calls something like:
val temp = Person.unapply(new Person("Magic", "Mike"))
if (temp != None) { val (x, y) = temp.get }
else { <go to next case> }
but how does below unapply work when i have like below:
new Person("Magic", "Mike") match {
case Person("Harold", y) => s"Last Name is ${y}"
case Person("Magic", y) => s"Last Name is ${y}"
case _ => "Unknown"
}
How does it access the value of fname("Magic") in unapply method and give me the same/correct result as the first one?