Junior — Middle
Can you explain how the data class is implemented and functions internally in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a data class is a special class designed for storing data. When compiled, the compiler automatically generates several useful methods for it:
equals()andhashCode()— for value-based comparison, not reference.toString()— for a 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.
Internally, a data class contains properties declared in the primary constructor, and access methods are generated for them. This reduces boilerplate code and makes working with such classes convenient and safe.
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