如何覆盖基类中的相等性?

时间:2014-07-30 22:58:34

标签: scala scala-2.10 type-erasure

我需要类似的东西:

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),还是必须始终在派生类中定义?

2 个答案:

答案 0 :(得分:1)

this.type是指this是唯一允许的值,因此case that: this.type相当于case that if that == thisthis.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]
}