Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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:

  1. 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.

  2. If for two objects the equals method returns true, then calling the hashCode method...