英文:
Kotlin get default hashCode implementation for inherited class
问题
在Kotlin/JVM中,每个类在重写之前都具有默认的equals/hashCode实现。Equals方法使用===
检查引用相等性,但hashCode是另一回事(我不知道它是什么)。
我想知道一旦被重写,是否可以恢复hashCode的默认实现,请考虑以下示例:
open class A {
override fun hashCode(): Int = 1
}
class B : A() {
override fun hashCode(): Int {
// 我如何在这里获取默认实现?..
}
}
英文:
Before overriding, each class in Kotlin/JVM has default equals/hashCode implementation. Equals is checking for reference equality with ===
, but hashCode is something else (and I don't know what it is).
I wonder if I can get the default implementation of hashCode back once overriden, consider this example:
open class A {
override fun hashCode(): Int = 1
}
class B : A() {
override fun hashCode(): Int {
// how can I get the default implementation here?..
}
}
答案1
得分: 6
你无法访问super.super方法,但JVM实际上提供了一种获取原始哈希码值的方法:
class B : A() {
override fun hashCode(): Int = System.identityHashCode(this)
}
英文:
You can't access to super.super methods, but the JVM actually provides a method to get the original hash code value:
class B : A() {
override fun hashCode(): Int = System.identityHashCode(this)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论