Overriding unapply method

后端 未结 2 731
说谎
说谎 2021-01-12 21:12

I have a case from a library class and I want to override unapply method to reduce the number of parameters I need to pass to

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 21:44

    case class MyClass(a: Int, b: String, c: String, d: Double /* and many more ones*/)
    object MyClassA {
       def unapply(x: MyClass) = Some(x.a)
    }
    
    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 custom unapply method in the MyClass object, because it would have to take a MyClass parameter, and there's already one such method there – one generated automatically for the case class. Therefore you have to define it in a different object (MyClassA in this case).

    Pattern matching in Scala takes your object and applies several unapply and unapplySeq methods to it until it gets Some with values that match the ones specified in the pattern.
    MyClassA(1) matches a if MyClassA.unapply(a) == Some(1).

    Note: if I wrote case m @ MyClassA(1) =>, then the m variable would be of type MyClass.

    Edit:

    a match {
        case MyClassA(x) => x  // x is an Int, equal to a.a
        case _ => ??? 
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题