如果我理解你的话,你已经通过覆盖 equals 完成了大部分的努力 - 当然你 MUST 也相应地覆盖 hashCode 例如:
case class Thing(id:Long, foo:String, bar:Int) {
override def equals(that:Any):Boolean = {
that match {
case Thing(_, f, b) => (f == this.foo) && (b == this.bar)
case _ => false
}
}
override def hashCode:Int = {
// A quick hack. You probably shouldn't do this for real;
// set id to 0 and use the default hashing algorithm:
ScalaRunTime._hashCode(this.copy(id = 0))
}
}
现在我们定义一些 Thing 实例:
val t1 = Thing(111, "t1", 1)
val t1c = Thing(112, "t1", 1) // Same as t1 but with a new ID
val t2 = Thing(222, "t2", 2)
val t3 = Thing(333, "t3", 3)
val t4 = Thing(444, "t4", 4)
val t4m = Thing(444, "t4m", 4) // Same as t4 but with a modified "foo"
让我们做几个序列:
val orig = Seq(t1, t2, t3, t4)
val mod = Seq(t1c, t2, t3, t4m)
现在diff告诉我们我们需要知道的一切:
mod.diff(orig)
// => returns Seq(t4m) - just what we wanted