choc (4) [Avatar] Offline
#1
I like the first two chapters, but I am wondering though about the relationship between hashCode() and ##. Typically they return the same thing and so I presume that AnyRef's ## simply returns hashCode(). So far so good. Things seem more complicated with number types though...

The following all evaluate to true:

1 == 1.0

1.## == 1
1.0.## == 1

1.hashCode() == 1
1.0.hashCode() == 1072693248

So hashCode() returns whatever is returned by the Java Integer and Double objects. This would invalidate the contract for == though as 1==1.0. Is this what motivated ##?

So,

Is it the general recommendation to override hashCode() but use ##?
Do all hash-based containers on Scala actually use ## (which for most types forwards to hashCode())?

Looking forward to the next installment of this book,

Dan
joshua.suereth (60) [Avatar] Offline
#2
Re: hashCode() and ## comparison
Yes. == and ## are defined by the compiler themselves to resolve issues with primitive/object mismatch in equals and hashCode.


So you are correct. In Scala you override equals and hashCode but call ## and ==. I think I need to make this one of my "callout" boxes in the chapter, or at least explicitly mention it. Thanks for the question!

As for Scala collections, they are using ##. However if you use Java Collections, they still use the raw hashCode.

Once again, the main difference between the two is for "AnyVal" values, so it's not a situation you won't run into, but it isn't the most common.