kotlinequality-operator

What is difference between == and === in kotlin


What is the difference between the comparison operators == and === in Kotlin?

class A {
  var foo = 1
}
    
var a1 = A()
var a2 = A()
    
println(a1 == a2)  // output false
println(a1 === a2) // output false
    
a1 = a2 
       
println(a1 == a2)  // output true
println(a1 === a2) // output true

Solution

  • In Kotlin, two types of equality are available. These are: Structural Equality & Referential Equality.

    class A {
      var foo = 1
    }
    
    var a1 = A()
    var a2 = A()
    

    Here a1 and a2 are two instances of class A.

    println(a1 == a2)
    

    It prints false because a1 and a2 are not structurally equal.

    println(a1 === a2)
    

    It prints false because a1 and a2 are not referencing the same object.

    But, if you execute this line: a1 = a2 then,

    a1 and a2 will be structurally equal and a1 is referencing to the a2 instance. That's why,

    println(a1 == a2)
    println(a1 === a2)
    

    both these lines returns true.