Equality evaluation in Kotlin

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 eqaulity –

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
    }
}

chevron_right


Output:

Two squares are structurally equal
Two squares are not referentially equal


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.