netzwerg netzwerg - 2 months ago 19
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

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)
}
Comments