hashCode and equals methods generated for you
Every type is derived from Any
, which comes with a hashCode
method declaration. This is the equivalent of a Java Object class hashCode
method. This method is important when you want to place your instances in collections, such as a map.
An object's hash code allows algorithms and data structures to place the instances in buckets. Imagine you implement a phone book. You'll place any name that starts with A in the A section, any name that starts with B in the B section, and so on. This simple approach allows you to have faster lookups when searching for someone. This is how hash-based collections, such as HashMap
and HashSet
, are implemented.
When implementing the method, you need to adhere to a contract:
- When invoked on the same object more than once during the runtime, the
hashCode
method must consistently return the same value, given the object was not modified. - If for two objects the
equals
method returns true, then calling the...