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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With