gpt4 book ai didi

kotlin - 等于 Kotlin 中的重载

转载 作者:IT老高 更新时间:2023-10-28 13:42:48 25 4
gpt4 key购买 nike

我试图为我的类(class)重载 compareToequals 运算符。

比较运算符没有问题。它既可以作为成员函数,也可以作为扩展函数。

equals 运算符必须是成员并且覆盖等于 fun。

class MyClass {
companion object {
private val NUMBER: Int = 5

operator fun compareTo(value: Int) = NUMBER - value

override operator fun equals(other: Any?) =
when (other) {
is Int -> NUMBER == other
else -> throw Exception("")
}
}
}

fun test() {
if (MyClass < 10) {
//ok
}

//Operator '==' cannot be applied to 'MyClass.companion' and kotlin.Int
if (MyClass == 5) {
}
}

编辑:如何正确重载'=='?

最佳答案

根据 this issue

定义 equalshashCode 被认为对没有显式父类(super class)型的 object 声明有些无用。 . object 上可能正确的 equals+hashCode 实现很少用例。

当您尝试这样做时,甚至有一个 IDE 检查会显示警告:

IDE warning screenshot
当对象具有声明的父类(super class)型时,警告不存在。

但是,我不认为某些技术原因会阻止 Kotlin 解决重载运算符,而且整个行为很奇怪,所以我提交了 an issue在 Kotlin 问题跟踪器中。

就目前而言(Kotlin 1.0.2 EAP),即使声明了父类(super class)型,您也只能检查 object完全相同的 声明 的实例是否相等类型 作为父类(super class)型:

object SomeObject : List<Int> by listOf() { ... }
SomeObject == listOf(1, 2, 3) // OK
SomeObject == arrayListOf(1, 2, 3) // not resolved (why?)

object MyObject : Any() { ... }
MyObject == 1 // error
MyObject == 1 as Any // OK o_O

object AnotherObject { ... }
AnotherObject == 1 as Any // works! Probably Any is supertype here

关于将equals定义为扩展函数:不,你不能这样做,因为 extensions are resolved statically 并且被成员遮蔽(有一个类似的 question about toString )。

关于kotlin - 等于 Kotlin 中的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com