Kotlin的平等 [英] Equality in Kotlin

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

问题描述

我正在学习Kotlin,具有C ++和Java背景。我期待以下内容打印 true ,而不是 false 。我知道 == 映射到等于的默认实现是否等于不比较每个成员,即 firstName lastName ?如果是这样,它不会看到字符串值相等(因为 == 再次映射到等于)?显然有一些与平等和身份相关的东西,我还没有在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"))
}


推荐答案

默认您描述的等于实现仅存在于数据类中。不适用于从 Object 继承实现的常规类,只需使对象等于它自己。

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

这篇关于Kotlin的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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