覆盖 unapply 方法 [英] Overriding unapply method
问题描述
我有一个来自库类的case,我想覆盖unapply
方法以减少我需要传递给的参数数量对其进行模式匹配.我这样做:
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 do pattern matching against 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"
}
}
但我希望它只返回 1
.这有什么问题吗?
But I want it to return just 1
. What's wrong with this?
推荐答案
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 _ => ???
}
你不能在 MyClass
对象中定义你的自定义 unapply
方法,因为它必须接受一个 MyClass
参数,而且已经有一个那里有这样的方法——一个为案例类自动生成的方法.因此,您必须在不同的对象中定义它(在本例中为 MyClassA
).
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).
Scala 中的模式匹配获取您的对象并对其应用多个 unapply
和 unapplySeq
方法,直到它获得 Some
的值与这些值匹配在模式中指定.MyClassA(1)
匹配 a
如果 MyClassA.unapply(a) == Some(1)
.
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)
.
注意:如果我写了 case m @ MyClassA(1) =>
,那么 m
变量将是 MyClass
类型.
Note: if I wrote case m @ MyClassA(1) =>
, then the m
variable would be of type MyClass
.
a match {
case MyClassA(x) => x // x is an Int, equal to a.a
case _ => ???
}
这篇关于覆盖 unapply 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!