In Kotlin, data class is designed for holding data. The compiler automatically generates the equals(), hashCode(), toString() methods, as well as the copy() and componentN() functions, which significantly simplify working with such objects:
data class User(val name: String, val age: Int) val u1 = User("Ivan", 30) val u2 = u1.copy(age = 31)
Regular classes do not have such auto-generated methods; everything has to be written manually. Data classes are better used for DTOs, models, and data structures.
Limitations of data classes:
val or var.abstract, open, sealed, or inner."Can a data class inherit from another data class? Why (or why not)?"
No, a data class cannot directly inherit from another data class. A data class can only inherit from an interface or a regular class (not a data class). This is done to prevent confusion with auto-generated methods (for example, copying inherited properties is not straightforward).
data class Base(val id: Int) data class Child(val name: String) : Base(1) // Compilation error: not allowed
Story
In a banking project, a data class was used with business logic and inheritance. After adding a new field, it became impossible to copy objects correctly, part of the business logic was lost (methods were not inherited), leading to errors in commission calculations.
Story
In an e-commerce platform, a data class was used to store the user's cart state. After updating the state via
copy(), they forgot that internal lists are not deeply copied. This led to data "leaking" between user sessions.
Story
In a project integrating an external API, serializing a data class to JSON resulted in fields with private visibility, violating the API contract and causing errors on the client side.