Difference between Structural and Referential Equality in Kotlin

In this tutorial, We will discuss two types of Equalities in Kotlin Programming Language.

Have you ever wondered what is the difference between == (Structural Equality) and === (Referential Equality)  in Kotlin?.

Equality types in Kotlin:

  1. Structural Equality (==)
  2. Referential Equality (===)

Let’s take an example of Vehicle class

data class Vehicle(var color: String, var model: Int, var company: String)
fun main(args: Array<String>) {

    var hondaOne = Vehicle("red", 2018, "Honda")

    // hondaTwo is initialized with hondaOne
    var hondaTwo = hondaOne            

    // Refrential Equality Check
    println("Output: ${hondaOne === hondaTwo}")    
    
    // Structural Equality Check
    println("Output: ${hondaOne == hondaTwo}")
     
}

The output of above program:

Output: true
Output: true

Since both hondaOne and hondaTwo object are same, hondaOne is assigned to hondaTwo so both Referential and Structural Equalities returns true.

Now let’s take another example:

This time we will not initialize hondaTwo with hondaOne, we will initialize hondaTwo separately.

fun main(args: Array<String>) {

 var hondaOne = Vehicle("red", 2018, "Honda")

 // this time hondaTwo object will get its own refrence. 
 var hondaTwo = Vehicle("red", 2018, "Honda") 

// Refrential Equality Check
 println("Output: ${hondaOne === hondaTwo}") 
 
// Structural Equality Check
 println("Output: ${hondaOne == hondaTwo}") 
}

The output of above program:

Output: false
Output: true

Because hondaOne and hondaTwo are initialized with same values, so their Structural Equality returned true.

But since they are different objects (they have the different reference in memory) so their Referential Equality resulted in false.

Another example

fun main(args: Array<String>) {
    

    var honda = Vehicle("red", 2018, "Honda")

    var toyota = Vehicle("black", 2017, "Toyota")

    println("Output: ${honda=== toyota}")
    println("Output: ${honda == toyota}")
}

The output of above program:

Output: false
Output: false

Note: For values which are represented as primitive type at run time for example (Int), the equality checks == and === are equivalent (behaves same).

Let’s learn through example

fun main(args: Array<String>) {
    
    var a = 100
    var b = 100

    println("Output: ${a == b}")
    println("Output: ${a === b}")
}

The output of above program:

Output: true
Output: true

We have learned about Structural and Referential Equality in Kotlin.

Recommended Reading:

Classes Objects Modifiers and Interfaces in Kotlin Tutorial

Enum Classes in Kotlin Tutorial

Kotlin Idioms Tutorial

Contact Us