我有一个case来自图书馆课程,我想覆盖unapply
method 减少参数数量我需要通过对其进行模式匹配。我这样做:
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
。这有什么问题吗?
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 _ => ???
}
您无法定义您的自定义unapply
方法中的MyClass
对象,因为它必须采取MyClass
参数,并且已经有一种这样的方法 - 为案例类自动生成的一种方法。因此你必须在不同的对象中定义它(MyClassA
在这种情况下)。
Scala 中的模式匹配获取您的对象并应用多个unapply
and unapplySeq
方法直到它得到Some
其值与模式中指定的值相匹配。
MyClassA(1)
火柴a
if MyClassA.unapply(a) == Some(1)
.
注意:如果我写case m @ MyClassA(1) =>
,那么m
变量的类型MyClass
.
Edit:
a match {
case MyClassA(x) => x // x is an Int, equal to a.a
case _ => ???
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)