Overriding the unauthorized access method

I have a class from the library class, and I want to override the unapply method to reduce the number of parameters . I need to pass to make a comparison with it, I do this:

 object ws1 { // a library class case class MyClass(a: Int, b: String, c: String, d: Double /* and many more ones*/) // my object I created to override unapply of class MyClass object MyClass { def unapply(x: Int) = Some(x) } val a = new MyClass(1, "2", "3", 55.0 /* and many more ones*/) a match { case MyClass(x /*only the first one is vital*/) => x // java.io.Serializable = (1,2,3,55.0) case _ => "no" } } 

But I want him to return only 1 . What is wrong with that?

+4
source share
2 answers
 case class MyClass(a: Int, b: String, c: String, d: Double /* and many more ones*/) object MyClassA { def unapply(x: MyClass) = Some(xa) } val a = new MyClass(1, "2", "3", 55.0 /* and many more ones*/) a match { case MyClassA(2) => ??? // does not match case MyClassA(1) => a // matches case _ => ??? } 

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 // x is an Int, equal to aa case _ => ??? } 
+6
source

I would put the overloaded unapply and just use the following to match:

 a match { case MyClass(x, _, _, _) => x // Result is: 1 case _ => "no" } 

EDIT:

If you really want to avoid unnecessary underscores, I think you need to look at something like:

 a match { case x:MyClass => xa case _ => "no" } 
+2
source

Source: https://habr.com/ru/post/1502590/


All Articles