Search code examples
javaoperator-overloadingkotlinoperatorsequality

Equality in Kotlin


I'm learning Kotlin, with a C++ and Java background. I was expecting the following to print true, not false. I know that == maps to equals. Does the default implementation of equals not compare each member, i.e. firstName and lastName? If so, wouldn't it see the string values as equal (since == maps to equals again)? Apparently there's something related to equality versus identity that I haven't got right in Kotlin yet.

class MyPerson(val firstName: String, val lastName: String)

fun main(args: Array<String>) {
   println(MyPerson("Charlie", "Parker") == MyPerson("Charlie", "Parker"))
}

Solution

  • The default equals implementation you're describing exists only for data classes. Not for regular classes where the implementation is inherited from Any, and just make the object equal to itself.