我需要类似的东西:
trait Base {
override def equals(other: Any): Boolean = other match {
case that: this.type => true
case _ => false
}
}
case class Derived() extends Base
但是,this.type
这里的模式匹配似乎是错误的方法,因为
val x = Derived()
val y = Derived()
x == y //always false
总是会产生假的。是否可以覆盖所有派生类的基类中的equals(也许通过使用ClassTag或TypeTag),还是必须始终在派生类中定义它?
这达到了目的:
trait Base {
type DerivedType <: Base
implicit def tag: ClassTag[DerivedType]
override def equals(other: Any): Boolean = validateType(other)
def validateType(other: Any): Boolean = other match {
case that: DerivedType => doSomethingAndReturnBoolean(that)
case _ => false
}
}
case class Derived() extends Base {
type DerivedType = Derived
override val tag = reflect.classTag[DerivedType]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句