...

/

Referential vs Structural Equality

Referential vs Structural Equality

The two fundamental types of equality and how to use them in Kotlin

Definition

In any programming language, we have two ways to compare objects and check if they are equal:

  • referential equality,
  • structural equality.

Referential equality of two objects means that they point to the exact same object in memory, i.e. they use the same reference.

Structural equality on the other hand means that two objects have the same value. They may still point to different places in memory though, i.e. they don’t necessarily hold the same reference.

Note: Referential equality implies structural equality.

In Kotlin, we have an operator for each of these:

  • Use === to check for referential equality
  • Use == to check for structural equality

Code Example

Press + to interact
val starters1 = listOf("charmander", "squirtle", "bulbasaur") // A list object
val starters2 = listOf("charmander", "squirtle", "bulbasaur") // Different list with same contents
println(starters1 === starters2) // false: the variables point to different memory locations
println(starters1 == starters2) // true: the variables hold equal values
println(starters1 !== starters2) // true: negation of first comparison
println(starters1 != starters2) // false: negation of second comparison

Whether two objects are structurally equal depends on their types, more specifically how their equals ...