Skip to main content

Equality (== or ===)

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

TypeCheckName
== same valuestructural
=== same referencereferential

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

How does it work?

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

  • it checks if first is null
  • if first IS null, it checks if second also references null
  • if first IS NOT null it checks if all the values in first are the same with all the values in second

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 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.

Anything else I should know ?

Structural equality checks work different with data classes. That requires a bit of it's own so I'll link it here when ready...

You can find out more in other bits, keep on browsing and add a reaction below or comment 😉 😉...