Is it possible to have two instances of the same d...
# getting-started
h
Is it possible to have two instances of the same data class with the same exact properties (and values) be equal but not have the same hashCode? I thought if the two instances are equal then their hashCode should be the same
r
By contract it should not happen, but if you have a malicious/badly implemented data class, then yes, such cases can happen. It is strongly discouraged, as a lot of structures rely on the implication
are equal => have same hashCode
you mentioned. (For example HashMap) One example of such situation is, if you make a data class and override equals (for example to ignore a property), and not override
hashCode
to match it (to ignore it too). TL;DR: yes, but only if data class is wrong. Don't do it.
If you have such case, then you need to find what class has bad hashCode that does not follow this contract - since usual hashCode relies on result of the properties hashCode, it can be anything in the structure. (Bad hashCode can be anything from it not entirely matching equals to just doing
Random.nextInt
)
h
Thanks I found the issue. My data class references another data class that overrides the hashCode method but that data class implements hashCode as
Copy code
override fun hashCode(): Int = super.hashCode()
And that data class's parent also implements:
Copy code
override fun hashCode(): Int = super.hashCode()
Does calling super.hashCode() mess with the hashCode? I find that weird
b
If
super
points to Any, than it produces identity hashcode (which has nothing to do with object's content)
r
By default data class implements "sane" hashcode calculated from it's code contents, if it's not overriden (same as it implements equals, copy and so...) If you override it and call super instead, it will be the identity one as mentioned above (if super is Any, which it likely is)
h
Thank you for the technical explanations 🙂 much appreciated