我有以下课程:
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
}
}
我也有几个具体的实现。但是,当我试图说出IRDMessage的任何子类型的a == b
时,不会调用equals方法,它只是比较引用(默认等于实现)。可能导致这种情况的任何想法?
子类是简单的案例类btw。
答案 0 :(得分: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
}
它没有按预期工作。