Junior — Middle
What is the role of the componentN field in Kotlin data class?
sobes.tech AI
Answer from AI
In Kotlin, for each property in a data class, functions componentN() are automatically generated, where N is the property’s ordinal number. These functions allow unpacking an object into individual variables through destructuring.
For example, if you have a data class:
data class User(val name: String, val age: Int)
the compiler will generate functions component1() for name and component2() for age. This allows you to write:
val user = User("Alice", 30)
val (name, age) = user // calls component1() and component2()
Thus, the role of componentN is to provide a convenient way to access the properties of an object through destructuring.