Operators: Equality, Inequality, and Comparison
Explore structural and referential equality and understand the use of comparison operators.
We'll cover the following
The equality and inequality operators
In Kotlin, there are two types of equality:
Structural equality: It is checked with the
equals
method or the==
operator (and its negated counterpart!=
).The statemenet
a == b
translates toa.equals(b)
whena
is not nullable. Otherwise, it translates toa?.equals(b) ?: (b === null)
.Structural equality is generally preferred over referential equality.
The
equals
method can be overridden in a custom class.
Referential equality: It is checked with the
===
operator (and its negated counterpart!==
).It returns
true
when both sides point to the same object.The
===
and!==
operators (identity checks) are not overloadable.
Get hands-on with 1200+ tech skills courses.