Sobes.tech
Junior — Middle

Are there any limitations or features of using data classes in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, data classes are designed for storing data and automatically generate equals(), hashCode(), toString() methods, as well as copy() functions and destructuring components.

Features and limitations:

  • Minimum requirement: a data class must have at least one parameter in the primary constructor.
  • Cannot be abstract, open, inner, or nested classes.
  • All primary constructor parameters automatically become properties.
  • It is not recommended to use data class for classes with logic; they should be purely for data.
  • If a data class has properties outside the primary constructor, they are not included in the automatically generated methods.
  • When inheriting, a data class cannot be open for inheritance (by default, it is final).

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(user2) // User(name=Alice, age=31)
Are there any limitations or features of using data… - sobes.tech