Kotlin 中的平等 [英] Equality in Kotlin
问题描述
我正在学习 Kotlin,具有 C++ 和 Java 背景.我期待以下打印 true
,而不是 false
.我知道 ==
映射到 equals
.equals
的默认实现是否不比较每个成员,即 firstName
和 lastName
?如果是这样,它会不会将字符串值视为相等(因为 ==
再次映射到 equal
)?显然,我在 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"))
}
推荐答案
您描述的默认 equals
实现仅适用于数据类.不适用于从 Any
继承实现的常规类,只需使对象等于自身即可.
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.
这篇关于Kotlin 中的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!