1

我有以下课程:

abstract class IRDMessage extends Ordered[IRDMessage] {

  val messageType: MessageType.Type
  val timestamp: DateTime
  val content: AnyRef

  def compare(that: IRDMessage): Int = {
    val res = timestamp compareTo that.timestamp
    res
  }

  override def equals(obj: Any): Boolean = obj match{
    case message: IRDMessage => compareTo(message) == 0
    case _ => false
  }

}

我也有几个具体的实现。但是,当我尝试说a == bIRDMessage 的任何子类型时,不会调用 equals 方法,它只是比较引用(默认 equals 实现)。有什么想法可能导致这种情况吗?

子类是简单的案例类。

4

1 回答 1

1

鉴于以下简化示例,这确实有效:

object MessageTest {
  def main(args: Array[String]) {
    val m1 = MessageImpl("foo")
    val m2 = MessageImpl("bar")
    m1 == m2
  }
}

abstract class IRDMessage extends Ordered[IRDMessage] {
  val content: AnyRef
  override def equals(obj: Any): Boolean = {
    println("in here")
    obj match{
      case message: IRDMessage => compareTo(message) == 0
      case _ => false
    }
  }

}

case class MessageImpl(content:String) extends IRDMessage{
  override def compare(that:IRDMessage) = 0
}

您能否发布更多代码,特别是您的示例案例类之一?我注意到如果我这样定义案例类:

case class MessageImpl extends IRDMessage{
  var content = "foo"
  override def compare(that:IRDMessage) = 0
}

它没有按预期工作。

于 2013-05-14T16:15:27.903 回答