Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

java - 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 equal 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"))
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Referential Equality

Java

In Java, the default implementation of equals compares the variable's reference, which is what == always does:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

We call this "referential equality".

Kotlin

In Kotlin == is compiled to equals, whereas === is the equivalent of Java's ==.

Structural Equality

Whenever we want rather structural than referential equality, we can override equals, which is never done by default for normal classes, as you suggested. In Kotlin, we can use data class, for which the compiler automatically creates an implementation based on the constructor properties (read here).

Please remember to always override hashCode if you override equals (and vice versa) manually and stick to the very strict contracts of both methods. Kotlin's compiler-generated implementations do satisfy the contract.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...