Sobes.tech
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(), and componentN() must be declared in the primary constructor.
  • Fields in a data class cannot be vararg or inline.
  • A data class cannot be abstract, open, sealed, or inner.
  • All primary constructor parameters must have at least the val or var modifier.

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.