Junior — Middle
Explain the working mechanism of the equals() method in Kotlin Data Class and how it differs from the standard implementation of equals().
sobes.tech AI
Answer from AI
In Kotlin, for classes with the data modifier, the compiler automatically generates an implementation of the equals() method. This method compares objects based on the values of their properties declared in the primary constructor, rather than by reference, as in the standard equals() implementation from the Any class.
The standard equals() method (for example, in Java or Kotlin without data) compares objects by reference — that is, it returns true only if both variables point to the same object in memory.
Example:
data class User(val name: String, val age: Int)
val user1 = User("Alice", 30)
val user2 = User("Alice", 30)
println(user1 == user2) // true, because property values are compared
// If User was a regular class without data:
class UserNormal(val name: String, val age: Int)
val user3 = UserNormal("Alice", 30)
val user4 = UserNormal("Alice", 30)
println(user3 == user4) // false, comparison by reference
Thus, equals() in a data class provides a convenient and correct way to compare objects by content, which is especially useful for data models.