gpt4 book ai didi

oop - 是否可以在 Kotlin 接口(interface)中编写 equals 方法的默认实现?

转载 作者:行者123 更新时间:2023-12-04 14:37:06 25 4
gpt4 key购买 nike

是否可以编写 equals 的默认实现? Kotlin 接口(interface)中的方法?

我有这个代码:

interface User {

val id: String

}

我希望所有实现 User 的类都使用 id 进行比较属性(property)。像这样的东西:
interface User {

val id: String

fun equals(other: Any?) : Boolean {
//check type and stuff
return id == other.id
}

}

我知道我可以(也许应该)使用抽象类,但我现在必须处理这种情况。

谢谢

最佳答案

不,恐怕这是不可能的。

如果您尝试您的代码,编译器会提示:
'equals' hides member of supertype 'Any' and needs 'override' modifier
如果您添加 override修饰符:
An interface may not implement a method of 'Any'
原因有点模糊,并且是从 Java 继承的(!)。

最初,接口(interface)只能包含抽象方法(和常量字段)。当添加在接口(interface)中指定方法实现的能力时,它是以一种不会破坏现有代码的方式完成的,因此它们仅适用于类还没有实现的地方。 (在 Java 中,它们被称为“默认”方法来强化这一点。)如果一个类有一个实现,无论是在类中还是在父类(super class)中定义,都会被使用,默认值被忽略。

不过也有一些极端情况:Object 中定义的方法(Java 相当于 Kotlin 的 Any )。那些是clone() , equals() , finalize() , getClass() , hashCode() , notify() , notifyAll() , toString() , 和 wait() . (其中大多数现在很少直接使用,但当然 equals()hashCode()toString() 非常重要。)

因为这些方法是在 Object 中定义的。 ,每个类都有它们的直接实现(来自 Object 或某个子类)。因此永远不能使用接口(interface)的默认实现。

Kotlin/JVM 和 Any 中定义的相应方法完全相同。 — 实际上,如果您尝试提供任何这些方法的默认实现,编译器会通过给出错误来明确说明,如上所示。

这是一种耻辱,因为在某些情况下,equals() 的默认实现是, hashCode() , 和/或 toString()将非常有用!但它会引入复杂性、脆弱性和一些令人惊讶的极端情况;见 this answer求权威解释。

关于oop - 是否可以在 Kotlin 接口(interface)中编写 equals 方法的默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60458192/

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