Last week we asked:
Kotlin supports multiple types of object equality. What are they? What are the differences?
There are 2 types of equality in Kotlin
- Referential Equality
- Structural Equality
Referential Equality
This type of equality is checked with the ===
operation and is negated by !==
. Consider a === b
. This will true if and only if a
and b
point to the SAME object.
⚠️ Note for primitive values like Int
, ===
is the same as ==
.
Structural Equality
This type of equality is checked with the ==
or .equals()
operation and has a negated counter part of !=
.
Consider a == b
. This is evaluate as:
a?.equals(b) ?: (b === null)
So if
a
is not
null
, then
.equals()
is called to compare
a
and
b
. If
a
is
null
, then
b === null
evaluates because of the
elvis operator (
?:
). This referential equality check determines if
b
is truly
null
and returns
true
if it is, and
false
if not.
Reply to this email or reach out on Twitter if you have any questions about equality in Kotlin!