ProgrammingBackend Developer

Explain the differences between data classes, regular classes, and inheritance classes in Kotlin. When should you use a data class and what limitations does the compiler impose?

Pass interviews with Hintsage AI assistant

Answer

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:

  • The primary constructor must have at least one parameter.
  • All constructor parameters must be marked as val or var.
  • Data classes cannot be abstract, open, sealed, or inner.
  • It is not recommended to use data classes for classes with business logic or inheritance hierarchy.

Trick Question

"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

Examples of real errors due to ignorance of the nuances of the topic


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.