Sobes.tech
Junior — Middle

What automatic methods are generated by the compiler for data classes and what are they intended for?

sobes.tech AI

Answer from AI

In Kotlin, the data class automatically generates several useful methods that facilitate working with objects:

  • equals() — for comparing objects by the value of all properties.
  • hashCode() — for obtaining a hash code consistent with equals().
  • toString() — returns a string representation of the object listing all properties.
  • copy() — creates a copy of the object with the ability to modify some properties.
  • componentN() functions — for destructuring the object into separate variables.

Example:

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

val user1 = User("Alice", 30)
val user2 = user1.copy(age = 31)

println(user1) // User(name=Alice, age=30)
println(user1 == user2) // false
val (name, age) = user2
println(name) // Alice
println(age) // 31

These methods simplify working with immutable objects and make the code more expressive.