I've read that Scala'a case class
construct automatically generates a fitting equals
and hashCode
implementation. What does exactly the generated code look like?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
- Run project with java options via sbt
As my professor used to say, only the code tells the truth! So just take a look at the code that is generated for:
We can instruct the Scala compiler to show us the generated code after the different phases, here after the typechecker:
So you can see that the calculation of the hash code is delegated to ScalaRunTime._hashCode and the equality depends on the equality of the case class' members.
Please be aware that the previous answers on this question are a bit outdated on the hashCode part.
As of scala 2.9
hashCode
for case classes usesMurmurHash
: link.MurmurHash produces good avalanche effect, good distribution and is CPU friendly.
The generated
hashCode
just callsscala.runtime.ScalaRunTime._hashCode
, which is defined as:So what you get is
elem1 * 41**n + elem2 * 41**(n-1) .. elemn * 1
, wheren
is the arity of your case class andelemi
are the members of that case class.Looks like things have changed; using Mirko's example
case class A(i: Int, s: String)
I get:and