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.
In this page:
Syntax
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
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
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
- Overriding
equalswithouthashCode, so equal objects have different hashes and behave incorrectly in aSetorMap. - Writing
def equals(other: Point), which overloads instead of overriding because the parameter must beAny. - Not handling the case where
otheris not aPoint, soequalsthrows aClassCastException.
Chapter Summary
- Classes have constructors, fields, and methods, with access modifiers controlling visibility.
- Companion objects hold related members.
- Case classes provide
toString,equals, andhashCode.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: