← Back to Scala Course | Chapter 7: OOP Basics | Lesson 7 of 7

toString, equals, and hashCode

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

markup
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)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.