Open In App

Equality evaluation in Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin provides an additional feature of comparing the instances of a particular type in two different ways. This feature makes Kotlin different than the other programming languages. 
The two types of equality are – 

  • Structural Equality
  • Referential Equality

Structural Equality –

Structural equality is checked through the == operator and its inverse != operator. By default, the expression containing x==y is translated into the call of equals() function for that type. 
 

x?.equals(y) ?: (y === null)

states that if x is not equal to null, it calls the function equals(y), otherwise if x is found to be null it will checks for y is referentially equal to null. 
Note – When (x == null) then automatically it will be converted to referential equality (x === null) so no need of code optimization here.
Thus, to use == on instances of a type the type must override the equals() function. For a string, the structural equality compares the contents.
 

Referential Equality –

The referential equality in Kotlin is checked through the === operator and its inverse !== operator. This equality returns true only if both the instances of a type point to the same location in memory. When used on types that are converted into primitives type at runtime, the === check is converted into == check and !== check is converted into != check.
Kotlin program to demonstrate the structural and referential equality – 

Java




class Square(val side: Int) {
    override fun equals(other: Any?): Boolean {
        if(other is Square){
            return other.side == side
        }
        return false
    }
}
// main function
fun main(args :Array<String>) {
    val square1 = Square(5)
    val square2 = Square(5)
    // structural equality
    if(square1 == square2) {
        println("Two squares are structurally equal")
    }
    // referential equality
    if(square1 !== square2) {
        println("Two squares are not referentially equal")
    }
}


Output: 
 

Two squares are structurally equal
Two squares are not referentially equal

 


Last Updated : 09 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads