When would you use a sealed class instead of an enum?
An enum class defines a fixed set of constants, each a single instance. It can have properties and methods, but every constant shares the same shape.
A sealed class or sealed interface restricts subclasses to the same package and module, giving a closed hierarchy where each subclass can hold different data.
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val code: Int) : Result()
object Loading : Result()
}
fun render(r: Result) = when (r) {
is Result.Success -> r.data
is Result.Error -> "error ${r.code}"
Result.Loading -> "loading"
}
Because the hierarchy is closed, when is exhaustive and the compiler warns about a missing branch when used as an expression. Use enums for simple named values, and sealed types for state machines, API responses and algebraic data types where each case carries different data.