hashCode()
relies on a mutable value SC-W1076The hashCode()
method computes and returns a hash for an object. This hash comes in handy during equality and hash-specific operations. It is recommended that if you're overriding this particular method to implement your custom logic, it is recommended that your logic not rely on a non-value field, i.e., a var
field. Entities declared using var
are mutable, whereas the ones declared using val
are immutable. In short, your hashCode()
logic relies on mutable entities and may generate an inconsistent hash value. It is therefore recommended that you either not rely on such mutable values or declare such values using val
.
class C {
// Mutable!
var v = 1
override def hashCode(): Int = {
val hash = v * 17
// Further compute `hash`
hash
}
}
class C {
// `v` is no longer mutable!
val v = 1
override def hashCode(): Int = {
val hash = v * 17
// Further compute `hash`
hash
}
}