Scala

Scala

Made by DeepSource

equals() and hashCode() must be overridden in pair SC-W1073

Bug risk
Critical

The equals() method indicates whether some other object is "equal to" this one whereas the hashcode() method returns a hash code value for the object. There is a general contract between both these methods that makes it mandatory to override both of them in pair. Failing to do so may violate this contract.

Briefly, the contract is defined as "equal objects must have equal hash codes". Not overriding the said methods in pair may adversely affect how objects and references are compared. Additionally, certain structures such as HashSet and HashMap rely on an object's hashcode. Generating a faulty or improper hashcode may result in hash collisions. Therefore, it is recommended that you either override the said methods in pair, or, not override them at all. If appropriate, consider using a case class instead. A case class is used to model immutable data and can fill both these methods appropriately without requiring you to do so.

Bad Practice

class C {
  override def equals(obj: Any): Boolean = ...
}

Recommended

class C {
  override def equals(obj: Any): Boolean = ...
  override def hashCode(): Int = ...
}

References: