class ColoredPoint(x: Int, y: Int, val color: Color.Value) extends Point(x, y) {
override def hashCode = 41 * super.hashCode + color.hashCode override def equals(other: Any) = other match {
case that: ColoredPoint => (that canEqual this) &&
super.equals(that) && this.color == that.color case _ =>
false
}
override def canEqual(other: Any) = other.isInstanceOf[ColoredPoint]
}
Listing 30.2 · A subclass equals method that calls canEqual.
stance, with the new class definitions, the comparison of p and pAnon would yield true. Here are some examples:
scala> val p = new Point(1, 2) p: Point = Point@6bc
scala> val cp = new ColoredPoint(1, 2, Color.Indigo) cp: ColoredPoint = ColoredPoint@11421
scala> val pAnon = new Point(1, 1) { override val y = 2 } pAnon: Point = $anon$1@6bc
scala> val coll = List(p)
coll: List[Point] = List(Point@6bc)
scala> coll contains p res16: Boolean = true
scala> coll contains cp res17: Boolean = false
scala> coll contains pAnon res18: Boolean = true
These examples demonstrate that if a superclass equals implementation defines and calls canEqual, then programmers who implement subclasses can
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index