case class MyClass(a: Int, b: String, c: String, d: Double ) object MyClassA { def unapply(x: MyClass) = Some(xa) } val a = new MyClass(1, "2", "3", 55.0 ) a match { case MyClassA(2) => ???
You cannot define your own unapply method in the MyClass object, because it will need to accept the MyClass parameter, and there is already one such method there - the one that is automatically generated for the case class. Therefore, you must define it in another object ( MyClassA in this case).
Matching the pattern in Scala transfers your object and applies several unapply and unapplySeq methods to it until it receives Some with values ββthat match those specified in the pattern.
MyClassA(1) matches a if MyClassA.unapply(a) == Some(1) .
Note: if I wrote case m @ MyClassA(1) => , then the variable m would be of type MyClass .
Edit:
a match { case MyClassA(x) => x
source share