João Freitas

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

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

TypeCheckName
==same valuestructural
===same referencereferential

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 if second.name is the same with first.name. That’s what we mean when we say it checks they have the same value

When we call == for any two objects it is translated to first?.equals(second) ?: (second === null) under the hood

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 and second point to different objects so it evaluates to false.

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 and second point to the same object in memory, if the name 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.

Structural equality checks work different with data classes.

#reads #kotlinbits #kotlin #equality