Sobes.tech
Junior — Middle

Which functions or methods in a data class automatically override basic operations?

sobes.tech AI

Answer from AI

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

  • equals() — for comparing objects by the value of their properties.
  • hashCode() — for proper functioning 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