Kotlin 中的平等 [英] Equality in Kotlin

查看:26
本文介绍了Kotlin 中的平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Kotlin,具有 C++ 和 Java 背景.我期待以下打印 true,而不是 false.我知道 == 映射到 equals.equals 的默认实现是否不比较每个成员,即 firstNamelastName?如果是这样,它会不会将字符串值视为相等(因为 == 再次映射到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆