When calling the get method of Scala’s HashMap class, which method is used to check if the key exists (i.e. whether a key in the map is equivalent to the supplied one)? Is it == or another one?
The Scala API does not clearly speak about it:
“Optionally returns the value associated with a key”
Hash maps first check hash value and then check identity. So the “method” is
(where
keyis the item you’re testing andentryis an item already in the map). In particular,scala.collection.immutable.HashMapuses exactly this form inside itsgetmethod (as of Scala version 2.9).If you want to change the behavior of identity, you therefore need to override
hashCodeand ofequals, and also you can’t rely upon overridden behavior of the item already in the map; it’s the one you test with whose equal method gets called. (But note that in general, no guarantee is made about whose equals method will be called, so you shouldn’t rely upon this behavior.)