Hashcode in immutable data classes


I would like to know if data classes that are immutable (containing only val) have String like optimized hashcode. I need said data classes to be as fast as possible as keys in a HashMap.

In other words, is it interresting to do this, or does the compiler do it for me?

data class Key(
        val bind: Bind, // This is also an immutable data type
        val argType: Type
) {
    private var _hashCode: Int = 0;

    override fun hashCode(): Int {
        if (_hashCode == 0)
            _hashCode = super.hashCode()
        return _hashCode


No, the hash code value is not stored in the implementation generated for the data classes. If that’s needed, the value should be stored manually.


Thanks :wink:


@udalov: is the implementation that I’ve shown in my first message correct?

Will calling super.hashCode() will call the data class generated hashCode function or just Any.hashCode?


No, super.hashCode() refers to the implementation in the super class (Any here). Unfortunately, there’s no way to reuse the automatically generated implementation: as soon as you declare your own hashCode() function, the implementation is not generated anymore. So you need to implement hashing logic manually from scratch, save the result of the computation to the backing property and call it in the hashCode() function body.


Issue opened here : https://youtrack.jetbrains.com/issue/KT-12991 :slight_smile:


It would be nice if Kotlin just implemented this optimization, so I wouldn’t need to implement it myself for every immutable data class I create (I think everywhere I’ve used data classes they have been effectively immutable). I suppose it would need to be opt-in somehow, as suggested in the related issue.