Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referential and structural equality in Kotlin

Tags:

kotlin

What is the difference between referential equality and structural equality in Kotlin?

val a = File("/myfile.txt")
val b = File("/myfile.txt")
val sameRef = a === b

and:

  val a = File("/myfile.txt")
    val b = File("/myfile.txt")
    val both= a == b
like image 833
Mohamed Amin Avatar asked Jun 15 '17 18:06

Mohamed Amin


1 Answers

  • Referential equality === (also called identity) means that the pointers for two objects are the same. That is to say the objects are contained in the same memory location which leads us to the fact that pointers reference to the same object.

    identity: determines whether two objects share the same memory address

  • Structural equality ==, in its turn, means that two objects have equivalent content. You should specify when two objects should be considered equal by overriding the equals() method.

    equality: determines if two object contain the same state.

As well as in Java, in Kotlin there're no specific equals() and hashCode() generated by default (not considering data classes). Thus, until you've overriden these methods for your class, both == and === perform identity comparison.

like image 133
Alexander Romanov Avatar answered Oct 22 '22 19:10

Alexander Romanov