Scala

Scala

Made by DeepSource

hashCode() relies on a mutable value SC-W1076

Bug risk
Critical

The 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.

Bad Practice

class C {
  // Mutable!
  var v = 1
  override def hashCode(): Int = {
    val hash = v * 17
    // Further compute `hash`

    hash
  }
}

Recommended

class C {
  // `v` is no longer mutable!
  val v = 1
  override def hashCode(): Int = {
    val hash = v * 17
    // Further compute `hash`

    hash
  }
}