Short, but interesting read. I’ve been using Kotlin for some time and didn’t know it also had the ===
equals operator, which shares the same syntax as JavaScript, but have completely different meanings (strict equality (JS) vs referential equality (Kt)).
tl;dr: ===
in Kotlin compares objects by reference
Why do we have two equality checks?
Because sometimes you want to check more than if the two object have the same value.
== checks if two objects have the same value
=== checks if two objects have the same reference
Type | Check | Name |
---|---|---|
== | same value | structural |
=== | same reference | referential |
What do you mean?
Let’s use an example
data class Author(val name: String = "Yoda")
>
val first = Author()
val second = Author()
println(first == second) // structural equality check
true
With structural equality it checks if the values in the two classes are the same, in this case it checks if second is of type
Author
and ifsecond.name
is the same withfirst.name
. That’s what we mean when we say it checks they have the samevalue
How does it work?
When we call
==
for any two objects it is translated tofirst?.equals(second) ?: (second === null)
under the hood
- it checks if
first
is null - if
first
IS null, it checks ifsecond
also references null - if
first
IS NOT null it checks if all the values infirst
are the same with all the values insecond
What about reference checks?
Okay, let’s go back to our example
data class Author(val name: String = "Yoda")
>
val first = Author()
val second = Author()
>
println(first === second) // referential equality check
false
A referential check validates if two variables point to the same object in memory. In the case above
first
andsecond
point to different objects so it evaluates tofalse
.
What if they point to the same object?
data class Author(val name: String = "Yoda")
val first = Author()
val second = first
>
println(first === second) // referential equality check
>
true
In this case,
first
andsecond
point to the same object in memory, if thename
property changes for the value both first and second will be updated. And this is what we mean when we say it checks the reference of two objects.
Anything else I should know ?
Structural equality checks work different with data classes.