Junior — Middle
What restrictions apply to fields in a data class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a data class has several restrictions on fields:
- All properties involved in
equals(),hashCode(),toString(),copy(), andcomponentN()must be declared in the primary constructor. - Fields in a
data classcannot bevarargorinline. - A
data classcannot be abstract, open, sealed, or inner. - All primary constructor parameters must have at least the
valorvarmodifier.
Example:
data class User(val name: String, val age: Int)
Here, name and age are properties that automatically participate in the data class methods. If a field is not declared in the primary constructor, it will not be considered in these methods.