Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 134 ยท Classes and Objects

Equality and Identity

Understand Kotlin equality: structural == versus referential ===, writing equals and hashCode correctly, NaN and arrays surprises, Comparable and why BigDecimal differs.

"Are these two things the same?" sounds like a simple question, yet it has two different answers in every object-oriented language. Two objects can be the same object (one box in memory, two names for it), or they can be different objects that hold equal data (two identical boxes). Mixing the two up is the source of many classic bugs: sets that contain duplicates, map lookups that return null, tests that fail only sometimes.

Kotlin makes the distinction explicit with two operators. == asks "are they equal?" (structural equality) and === asks "are they the very same object?" (referential equality). This lesson explains both, shows how to write a correct equals/hashCode pair, and walks through the surprises: NaN, arrays, BigDecimal and ordering with Comparable. It builds on Classes and Properties and Data Classes.

== and ===

In Kotlin, a == b is translated to a?.equals(b) ?: (b === null). That means it calls the equals function of a, but safely: if a is null, the result is simply whether b is null too. No NullPointerException, and no need for Objects.equals. The operator a === b compares references and never calls equals.

Kotlin Structural versus referential equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For String, == compares the characters. For a class you write yourself, == does whatever equals does, and by default that is the same as ===.

Default equality is identity

Kotlin A plain class compares by identity until you say otherwise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The data class generates equals from its constructor properties, the plain class inherits the identity-based equals from Any. Use a data class when equality should follow the data, and a normal class when each instance is its own entity (a database connection, a user session, a thread).

Writing equals and hashCode yourself

Sometimes a data class does not fit, for example if only some properties should count. Then you override equals and hashCode together. The equals contract says:

  • Reflexive: x == x is true.
  • Symmetric: x == y implies y == x.
  • Transitive: x == y and y == z imply x == z.
  • Consistent: repeated calls give the same answer while the objects do not change.
  • Null-safe: x.equals(null) is false.

and hashCode must obey: if two objects are equal, their hash codes must be equal. (The reverse is not required: different objects may share a hash code.)

Kotlin A correct equals and hashCode pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the pattern: === first as a cheap shortcut, then a type check with is (the smart cast gives access to other.id), then compare the fields that define identity. Two employees with the same id are the same person, even when their names differ.

What goes wrong without hashCode

Hash-based collections (HashSet, HashMap, LinkedHashMap, and therefore setOf and mapOf) first use hashCode to pick a bucket and only then call equals inside it. If you override equals but not hashCode, equal objects usually have different hash codes (the default one is derived from the object's identity) and the collection never gets as far as equals:

Kotlin equals without hashCode breaks hash collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program does not crash; it lies. == says the tags are equal, but the set answers that it does not contain second and grows to two "equal" entries, while List.contains (which only uses equals) says true. The exact set answers depend on the identity hash codes, so in rare cases two hash codes collide and the bug hides; that is what makes it so nasty. The fix is a one-line hashCode: override fun hashCode() = name.hashCode(). For several fields, combine them with Objects.hash(a, b, c) or 31 * a.hashCode() + b.hashCode().

If you find yourself writing equals by hand for a plain value-holder, ask whether a data class or a value class already does exactly this. Hand-written equals is mostly for entities that compare by id, or for classes where only some fields count.

Operators refuse nonsense

Kotlin checks == at compile time. Comparing types that can never be equal is an error, not a silent false:

Kotlin Comparing unrelated types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with error: operator '==' cannot be applied to 'String' and 'Int'. In Java the same comparison compiles and is always false. Convert one side (name == number.toString() or name.toInt() == number).

Surprises worth knowing

Floating point: NaN and negative zero

Double.NaN ("not a number") is not equal to anything under the IEEE rules, including itself. Kotlin follows those rules when the compiler knows the static type is Double, and the stricter equals rules when the value is treated as Any or Comparable, or put into a collection:

Kotlin NaN and -0.0

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Use isNaN() to test for NaN, and never use == on floating-point results of calculations: compare with a tolerance (abs(a - b) < 1e-9).

Arrays use identity

An array's equals is inherited from Any, so == compares references, not contents. Lists do the right thing:

Kotlin Arrays versus lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Printing an array directly shows an unhelpful [I@1b2c3d; use contentToString(). Data classes with array properties inherit this problem: their generated equals calls == on the array and finds two different objects. Prefer lists in data classes.

Comparable: equality's cousin

Comparable<T> adds compareTo, which orders objects (negative, zero or positive). It powers <, >, sorted(), maxOrNull() and sorted collections. The recommended rule is that compareTo should return 0 exactly when equals is true. Standard-library classes occasionally break it, and BigDecimal is the famous case: 1.0 and 1.00 have different scales, so equals says no, while compareTo says they are numerically equal.

Kotlin compareTo versus equals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Sorted sets and maps such as java.util.TreeSet treat "compareTo is 0" as "same element", so a TreeSet<BigDecimal> holds only one of 1.0 and 1.00, while a HashSet holds both. When in doubt, normalize first (stripTrailingZeros()). Sorting by several fields is covered in Sorting and Comparators.

Pitfalls checklist

  • Override equals and hashCode together, using the same fields in both.
  • Do not use mutable fields in hashCode if the object is used in a set or as a map key; see Object Basics: toString, equals, hashCode.
  • Never compare floating-point results with ==.
  • Use contentEquals for arrays, or prefer lists.
  • Use === only when identity is really the question (a sentinel object, an object cache, tests).
  • For inheritance hierarchies, symmetric equality is hard: Point equal to ColorPoint but not vice versa is a classic bug. Prefer data classes, sealed hierarchies and composition.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a == b do in Kotlin when a is not null?

    == is structural equality: it calls equals (null-safely). The operator === compares references.
  2. 2. A class overrides equals but not hashCode. What is the most likely visible symptom?

    Equal objects get different identity-based hash codes, so a HashSet looks in the wrong bucket and keeps both. The compiler does not enforce the pair.
  3. 3. What does Double.NaN == Double.NaN evaluate to when both sides have the static type Double?

    IEEE 754 says NaN is not equal to anything, including itself. Use isNaN(). Via equals() on a boxed value, NaN equals NaN.
  4. 4. Why does intArrayOf(1, 2) == intArrayOf(1, 2) print false?

    Array does not override equals. Use contentEquals() to compare contents.
  5. 5. BigDecimal("1.0") == BigDecimal("1.00") is false while compareTo returns 0. Why?

    BigDecimal.equals requires equal value and scale; compareTo ignores the scale. Sorted collections follow compareTo, hash collections follow equals.

Summary

  • == is structural equality (calls equals, null-safe); === is referential equality and never calls equals.
  • The default equals from Any is identity; data classes generate property-based equals and hashCode.
  • Override equals and hashCode as a pair; equal objects must have equal hash codes.
  • equals must be reflexive, symmetric, transitive, consistent and false for null.
  • == between unrelated types does not compile.
  • NaN, -0.0 and arrays behave unusually; use isNaN(), tolerances and contentEquals.
  • compareTo should agree with equals; BigDecimal is the well-known exception.

Next: Object Basics: toString, equals, hashCode