Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case class with cached hashCode

Tags:

scala

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
like image 670
Rahel Lüthy Avatar asked Sep 29 '16 16:09

Rahel Lüthy


2 Answers

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)
}
like image 194
Alvaro Carrasco Avatar answered Oct 14 '22 00:10

Alvaro Carrasco


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.

like image 4
vvg Avatar answered Oct 14 '22 01:10

vvg