Sobes.tech
Junior — Middle

Welche Funktionen oder Methoden in der Datenklasse erhalten automatisch die Überschreibung der Basiseingaben?

sobes.tech KI

Antwort von AI

In Kotlin, when declaring a class with the keyword data, the following methods are automatically overridden:

  • equals() — for comparing objects by the value of their properties.
  • hashCode() — for correct operation with hash collections.
  • toString() — for convenient string representation of the object.
  • copy() — for creating a copy of the object with the ability to modify some properties.
  • componentN() functions — for destructuring the object by properties.

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) = user1
println(name) // Alice