我需要类似的东西:
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),还是必须始终在派生类中定义?
答案 0 :(得分:1)
this.type
是指this
是唯一允许的值,因此case that: this.type
相当于case that if that == this
。 this.type
未引用this
的类。
您可以使用反射在equals
中定义Base
:
override def equals(other: Any): Boolean = other.getClass == getClass
但是,如果没有反射,则必须在每个子类中定义equals
。
答案 1 :(得分:0)
这就是诀窍:
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]
}