Junior — Middle
What components or elements does a Kotlin class marked as data automatically create?
sobes.tech AI
Answer from AI
A class marked with data in Kotlin automatically receives the following components:
equals()method — compares objects by the value of their properties.hashCode()method — computes a hash code based on properties.toString()method — provides a string representation of the object listing its properties.copy()method — creates a copy of the object with the ability to modify some properties.- Decomposition functions (
componentN()) — allow unpacking 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)
val (name, age) = user2
println(name) // Alice
println(age) // 31