8

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
2

1 Answer 1

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.