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

toString, equals, and hashCode

toString, equals, and hashCode decide how an object is shown as text, how two objects are compared, and how they are filed in fast lookups. Defining them yourself makes your objects behave sensibly.
Syntax
scala
class ClassName(val field: Type) {
  override def toString: String = s"ClassName($field)"
  override def equals(other: Any): Boolean = other match {
    case that: ClassName => field == that.field
    case _ => false
  }
  override def hashCode: Int = field.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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Overriding equals without hashCode, so equal objects have different hashes and behave incorrectly in a Set or Map.
  2. Writing def equals(other: Point), which overloads instead of overriding because the parameter must be Any.
  3. Not handling the case where other is not a Point, so equals throws a ClassCastException.
Chapter Summary
  • Classes have constructors, fields, and methods, with access modifiers controlling visibility.
  • Companion objects hold related members.
  • Case classes provide toString, equals, and hashCode.
🔒

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.