I’ve tried the code below (the equal method is written after Programming in Scala book)
class Person() {
class Room(r: Int, c: Int) {
val row = r
val col = c
override def hashCode: Int =
41 * (
41 + row.hashCode
) + col.hashCode
override def equals(other: Any) =
other match {
case that: Room =>
(that canEqual this) &&
this.row == that.row &&
this.col == that.col
case _ => false
}
def canEqual(other: Any) =
other.isInstanceOf[Room]
}
val room = new Room(2,1)
}
val p1 = new Person()
val p2 = new Person()
println(p1.room == p2.room)
>>> false
After some analysing I found that Scala redefines the class Room for each instance of Person and that’s the reason the two rooms aren’t equal.
One possibility to resolve the problem is to put the class outside of the class Person, but this isn’t always what’s easiest. (For example if the class has to access some parameters of Person.)
What alternatives are there to write the equal method?
The problem is that your two rooms are instances of a path-dependent type: their types are
p1.Roomandp2.Room:One way to make this work is to refer to
Roomusing type selection, i.e. asPerson#Room.