Home > other >  Method hashCode in classes and case classes
Method hashCode in classes and case classes

Time:10-07

I hope this answer is not duplicated, I tried searching and I think it wasn't asked before.

From the Scala documentation I can read (https://docs.scala-lang.org/overviews/scala-book/case-classes.html ):

...
`equals` and `hashCode` methods are generated, which let you compare objects and easily use them as keys in maps.
...

So I have this code:

class Person_Regular(name: String)
case class Person_CC(name: String)

If I print the result of hashCode():

println(Person_CC("a").hashCode()) 

I can see in the console:

-1531820949

It make sense because case class contains the method hashCode by default. What about a regular class?

This code:

println((new Person_Regular("Joe")).hashCode())

Also prints the hash code:

1018937824

So when defining a class the method hashCode is also generated automatically? Then why the Scala documentation says the hashCode is generated with case classes when regular classes already do it?

CodePudding user response:

So when defining a class the method hashCode is also generated automatically?

No. For ordinary classes, it's just inherited from java.lang.Object / AnyRef, and it's based on the identity of the object, not on its contents:

class A(name: String)
case class B(name: String)

println(A("x").hashCode != A("x").hashCode) // true: hash codes are different
println(B("x").hashCode == B("x").hashCode) // true: hash codes are the same

In the first case, the hash codes are allowed to differ, because the objects are not referentially equal.

In the second case, the hash codes are derived from the contents of the case class in a predictable way, and are therefore the same.

  • Related