toString, equals, and hashCode
In this page:
toString, equals, and hashCode
By default, a plain class's toString prints an unhelpful representation like Point@1a2b3c, since Scala inherits Java's default Object.toString. Overriding toString, equals, and hashCode gives a class readable printing and correct value-based comparison/hashing (important for use in Set/Map). Case classes generate all three automatically, which is why they're usually preferred over manually overriding them in a plain class.
Note: If you override equals, you should also override hashCode to keep them consistent -- or just use a case class, which handles both correctly.
Example: toString, equals, and hashCode
class Point(val x: Int, val y: Int) {
override def toString: String = s"Point($x, $y)"
override def equals(other: Any): Boolean = other match {
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
override def hashCode(): Int = (x, y).hashCode()
}
object Main extends App {
val p1 = new Point(1, 2)
val p2 = new Point(1, 2)
println(p1)
println(p1 == p2)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: