Sobes.tech
Junior — Middle

What features and limitations do data classes in Kotlin have?

sobes.tech AI

Answer from AI

Data classes in Kotlin are designed for storing data and automatically generate useful methods: equals(), hashCode(), toString(), copy(), and componentN() functions.

Features and restrictions:

  • Must have at least one parameter in the primary constructor.
  • All constructor parameters declared in the primary constructor automatically become properties.
  • Cannot be abstract, open, inner, or inherit from other classes (but can implement interfaces).
  • Methods are generated only for properties declared in the constructor.
  • You can override generated methods if behavior needs to be changed.

Example:

data class User(val name: String, val age: Int)

val user1 = User("Alice", 30)
val user2 = user1.copy(age = 31) // creates a new object with changed age
println(user1) // User(name=Alice, age=30)
What features and limitations do data classes in… - sobes.tech