netzwerg netzwerg - 1 year ago 164
Scala Question

Scala case class with cached hashCode

I was under the impression that the hashCode of a Scala case class was solely determined by its fields. Consequently, I thought that caching a hashCode was safe for immutable case classes.

Seems like I am wrong:

case class Foo(s: String) {
override val hashCode: Int = super.hashCode()

val f1 = Foo("foo")
val f2 = Foo("foo")

println(f1.hashCode == f2.hashCode) // FALSE

Could anyone explain what's going on here, please?

Addendum – Just for comparison:

case class Bar(s: String)

val b1 = Bar("bar")
val b2 = Bar("bar")

println(b1.hashCode == b2.hashCode) // TRUE

Answer Source

Not sure about the value of this, but you can inline the implementation of ScalaRuntime._hashCode:

case class Foo(s: String) {
  override val hashCode: Int = scala.util.hashing.MurmurHash3.productHash(this)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download