Sobes.tech
Junior — Middle

Milliseid automaatseid meetodeid loob kompilaator andmesklassi jaoks ja milleks need on mõeldud?

sobes.tech AI

Vastus AI-lt

In Kotlin, for data class, the compiler automatically generates several useful methods that make working with objects easier:

  • equals() — to compare objects based on the value of all properties.
  • hashCode() — to obtain 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.