Referential and structural equality in Kotlin

2020-04-10 06:47发布

问题:

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

回答1:

  • 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.



标签: kotlin