Sobes.tech
Junior — Middle

Is it permissible to apply the sealed modifier for declaring data classes in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, you cannot declare a data class with the sealed modifier.

The reason is that sealed classes are intended to restrict inheritance hierarchy — all subclasses must be declared in the same file. Data classes, on the other hand, are meant for storing data with automatically generated methods (equals, hashCode, toString, etc.).

The combination of sealed and data class is not supported because a sealed class cannot be a data class, but its subclasses can be data classes.

Example:

sealed class Result

data class Success(val data: String) : Result()
data class Error(val error: Throwable) : Result()

Here, the sealed class Result restricts inheritance, and its subclasses are data classes.

Is it permissible to apply the sealed modifier for… - sobes.tech