Junior — Middle
Kas saaksite selgitada, kuidas data class Kotlinis sisemiselt rakendatud ja toimib?
sobes.tech AI
Vastus AI-lt
In Kotlin, data class is a special class designed for storing data. During compilation, the compiler automatically generates several useful methods:
equals()andhashCode()— for comparing objects by value, not by 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 avoids repetitive code and makes working with such classes more 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