What is the difference between `##` and `hashCode`?

“Subclasses” of AnyVal do not behave properly from a hashing perspective:

scala> 1.0.hashCode
res14: Int = 1072693248

Of course this is boxed to a call to:

scala> new java.lang.Double(1.0).hashCode
res16: Int = 1072693248

We might prefer it to be:

scala> new java.lang.Double(1.0).##
res17: Int = 1

scala> 1.0.##
res15: Int = 1

We should expect this given that the int 1 is also the double 1. Of course this issue does not arise in Java. Without it, we’d have this problem:

Set(1.0) contains 1 //compiles but is false

Luckily:

scala> Set(1.0) contains 1
res21: Boolean = true

Leave a Comment

tech