Effective Kotlin: Item 11 — Always override hashCode when you override equals

Matthew Dolan
2 min readFeb 27, 2018

In Effective Java by Joshua Bloch, there are lots of details about how to write a hashCode function. With Kotlin’s data class implementation, there is now often little need to write your own as it provides one for you.

As with item 10 which talks about implementing equals, the main premise is to calculate the hashCode based off your classes significant fields with the more unique the value, the better it is for storing in hash tables. Consider a data class which has a unique identifier, id:

data class User(val id: Int, val name: String, val age: Int)

The hashCode function generated is:

public int hashCode() {
return (id * 31 + (name != null?name.hashCode():0)) * 31 + age;
}

Although there’s nothing wrong with this per se, it will return results as expected, if you already have a unique value, such as id, simply using that for the hashcode would be much more performant as it would be with equals too.

override fun hashCode(): Int {
return id
}

Kotlin’s data types of Int, Long, etc. provide hashCode functions, and it may be tempting to use these, however, note that this will involve boxing and unboxing. id.hashCode() compiles as:

Integer.valueOf(id).hashCode();

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Join medium to read all of my articles or subscribe for e-mail updates.

--

--

Matthew Dolan

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.