Sobes.tech
Middle

Is it always necessary to override the equals method in a data class?

sobes.tech AI

Answer from AI

Not always. A data class in Kotlin automatically generates equals(), hashCode(), and toString() methods based on the properties defined in the primary constructor.

If you want to change the object comparison logic of a data class, for example, to ignore some properties during comparison, then you must override the equals() method.

If the standard comparison of all properties in the primary constructor suits you, overriding equals() is not necessary.

Example:

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

// Standard comparison: objects are equal if all properties are equal
val user1 = User(1, "Alice", "alice@example.com")
val user2 = User(1, "Alice", "alice@example.com")
val user3 = User(2, "Bob", "bob@example.com")

// user1 == user2 (true)
// user1 == user3 (false)

data class Product(val id: Int, val name: String, val price: Double) {
    // Override equals to compare only by id
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Product

        if (id != other.id) return false

        return true
    }

    // It's also important to override hashCode() when overriding equals()
    override fun hashCode(): Int {
        return id
    }
}

val product1 = Product(101, "Laptop", 1200.0)
val product2 = Product(101, "Desktop", 1000.0) // Different name and price, but same id

// product1 == product2 (true, since only id is compared)
Is it always necessary to override the equals method… - sobes.tech