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
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)
}
Not sure what you mean by "cached hasCode", but ...
You've override hashCode
with custom solution that built from Object
, that is why you're getting false
. Remove this override and you'll get expected value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With