Search code examples
kotlinhashcode

Kotlin get default hashCode implementation for inherited class


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?..
    }
}

Solution

  • 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)
    }