Equality in Kotlin

Referential Equality

Java

In Java, the default implementation of equals compares the variable’s reference, which is what == always does:

The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null
reference values x and y, this method returns true if and only if x
and y refer to the same object (x == y has the value true).

We call this “referential equality”.

Kotlin

In Kotlin == is compiled to equals, whereas === is the equivalent of Java’s ==.

Structural Equality

Whenever we want rather structural than referential equality, we can override equals, which is never done by default for normal classes, as you suggested. In Kotlin, we can use data class, for which the compiler automatically creates an implementation based on the constructor properties (read here).

Please remember to always override hashCode if you override equals (and vice versa) manually and stick to the very strict contracts of both methods. Kotlin’s compiler-generated implementations do satisfy the contract.

Leave a Comment

tech