Skip to content
DeveloperMemos

Kotlin Tips: Overriding equals

Kotlin, Android Development1 min read

When working with Kotlin, understanding how to properly override the equals method is crucial as it directly impacts the behavior of object comparisons. In this article, we'll delve into the significance of overriding equals and provide practical examples to illustrate its implementation.

Importance of Overriding Equals

The equals method in Kotlin is used to compare objects for equality. By default, it performs reference equality, which means it checks if two references point to the same object in memory. However, in many scenarios, we need to define our own criteria for equality based on specific attributes or properties of objects. This is where overriding the equals method becomes essential.

Implementing Custom Equality Checks

Let's consider a simple example involving a Person class. We want to compare two Person objects based on their names and ages:

1data class Person(val name: String, val age: Int) {
2 override fun equals(other: Any?): Boolean {
3 if (this === other) return true
4 if (other !is Person) return false
5 return this.name == other.name && this.age == other.age
6 }
7}

In this example, we override the equals method to compare Person objects based on their name and age properties. We first perform reference equality check using === and then proceed to compare individual properties. By doing so, we establish our own custom equality criteria.

Ensuring Symmetry and Consistency

When overriding the equals method, it's important to ensure that the comparison follows certain principles. The comparison should be symmetric, meaning if a.equals(b) returns true, then b.equals(a) should also return true. Additionally, the comparison should remain consistent across different calls.

Handling Nullability

To handle nullability when implementing custom equals methods, the == operator can be utilized. For instance, in the Person class example, if we want to consider two Person objects equal even if one of them has a null name:

1data class Person(val name: String?, val age: Int) {
2 override fun equals(other: Any?): Boolean {
3 if (this === other) return true
4 if (other !is Person) return false
5 return (this.name == other.name || this.name == null || other.name == null) && this.age == other.age
6 }
7}

By incorporating null checks within the equals method, we can accommodate scenarios where certain properties might be nullable.


Overriding the equals method is an important aspect of defining custom equality checks in Kotlin. By doing so, we can tailor object comparisons to suit specific requirements, ensuring that our code behaves as expected when performing equality checks. Understanding the nuances of overriding equals allows us to create robust and predictable equality comparisons tailored to our application's needs.