Problem with equals()
The problem with equals() is that it is difficult to get it right. For example, for a simple class Foo, you may write the equals() method as:
class Foo(val i: Int) {
override def equals(that: Any) = {
that match {
case f: Foo => f.i == i
case _ => false
}
}
}
The problem is that what happens if the other object ("that") belongs to a subclass of Foo, which may have its own fields? As the equals() method is only comparing the "i" field, it will ignore the other fields and return true prematurely. Below is such a subclass Bar:
class Bar(i: Int, val j: Int) extends Foo(i) {
override def equals(that: Any) = {
that match {
case b: Bar => super.equals(b) && b.j == j
case _ => false
}
}
}
With the erroneous equals() method in Foo, we could get incorrect results:
scala> val f1 = new Foo(2)
f1: Foo = Foo@14c0275
scala> val b1 = new Bar(2, 3)
b1: Bar = Bar@171bc3f
scala> f1.equals(b1)
res0: Boolean = true
scala> b1.equals(f1)
res1: Boolean = false
A solution to the problem
The problem is that the equals() method in Foo is treating the Bar object exactly as a base Foo object, but the equality contract in Bar has changed from that in Foo. Of course, not every subclass of Foo will use a different equality contract; some do and some don't (by default, we should assume that they don't). Therefore, the equals() method in Foo should make sure that the "that" object uses the same equality contract as "this":
object FooEqualityContract {
}
class Foo(val i: Int) {
//by default all Foo objects and subclass objects use this equality contract
val equalityContract: Any = FooEqualityContract
override def equals(that: Any) = {
that match {
//make sure the two objects are using the same equality contract
case f: Foo => f.equalityContract == this.equalityContract && f.i == i
case _ => false
}
}
}
Now, as Bar is using its own equality contract, it should say so:
class Bar(i: Int, val j: Int) extends Foo(i) {
//tell others that we're using our own equality contract
override val equalityContract: Any = BarEqualityContract
override def equals(that: Any) = {
that match {
case b: Bar => super.equals(b) && b.j == j
case _ => false
}
}
}
Now, the equals() method in Foo will rightly determine that a Bar object is using a different equality contract and thus will never be equal to a bare Foo object:
scala> val f1 = new Foo(2)
f1: Foo = Foo@34b350
scala> val b1 = new Bar(2, 3)
b1: Bar = Bar@7c28c
scala> f1.equals(b1)
res2: Boolean = false
scala> b1.equals(f1)
res3: Boolean = false
scala> val b2 = new Bar(2, 3)
b2: Bar = Bar@5dd915
scala> b1.equals(b2)
res6: Boolean = true
Of course, it should also work for subclasses that use the same equality contract:
scala> val f2 = new Foo(2) { }
f2: Foo = $anon$1@a594e1
scala> f1.equals(f2)
res9: Boolean = true
scala> f2.equals(f1)
res10: Boolean = true
No comments:
Post a Comment