This article explores different ways to use equal objects as a key in Map or Set in Kotlin.

The default implementation of equals() and hashCode() functions simply checks for the reference equality. This can be problematic if an object is used as a key for Map or Set, and its class does not override equals and hashcode function.

 
For instance, user1 and user2 have equal values of each field in the following example, but they are considered as two different objects by the Set.

Download Code

Output:

[{Brad, 18}, {Brad, 18}, {Steve, 16}]

 
You can make Map or Set treat two separate objects, with the same value, as the same by overriding the equals and hashcode function.

Download Code

Output:

[{Steve, 16}, {Brad, 18}]

 
Alternatively, you can use a data class that automatically implements the equals() and hashCode().

Download Code

Output:

[User(name=Brad, age=18), User(name=Steve, age=16)]

That’s all about using equal objects as a key in Map or Set in Kotlin.