我已经覆盖equals了数据类中的方法Point:
data class Point(val x: Int, val y: Int) {
companion object {
val TAG = "Kotlin"
}
override fun equals(other: Any?): Boolean {
Log.d(TAG, "overrided equals")
if (other === this) return true
if (other !is Point) return false
return other.x == x && other.y == y
}
}
我正在尝试按如下方式测试此方法:
Log.d(TAG, "${Point(1, 2) == Point(1, 2)}")
Log.d(TAG, "${Point(1, 2) != Point(1, 5)}")
Log.d(TAG, "${null == Point(1, 2)}")
Log.d(TAG, "${Point(1, 2) == null}")
但在控制台中执行此代码后,我得到:
覆盖等于
真的
覆盖等于
真的
错误的
错误的
由此可见, equals仅在前两次比较中调用了被覆盖的方法。为什么不要求第三次比较对我来说也很清楚(因为“Kotlin 中的运算符默认不支持交换性(反转操作数)”)。但我不明白为什么 equals最后一次,第四次比较不调用覆盖的方法(Point(1, 2) == null)......
毕竟,值null必须包含在许多类型Any?中。例如,代码
val n = null
Log.d(TAG, "null ${if (n is Any?) "is" else "isn't"} type of Any?")
返回
null 是 Any 的类型?
因此,这个比较必须匹配被覆盖方法的签名(override fun equals(other: Any?): Boolean)......为什么这个比较没有调用被覆盖的方法?
事实是,在 Kotlin 中,变量
a == null所在的表达式会自动转换为形式,并且无法重新定义运算符。aa === null===