Kotlin Sealed Classes
A sealed class or interface defines a closed family of subtypes: all direct subclasses must be declared in the same package and module, so the compiler knows the complete list. That makes sealed types ideal for modelling states and results where each case carries different data.
Enum vs. sealed
| Enum | Sealed class | |
|---|---|---|
| Number of cases | fixed | fixed |
| Each case is | a single instance | a class — can have many instances |
| Data per case | same properties for all | each subclass has its own properties |
Exhaustive when |
yes | yes |
A result type
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val code: Int, val message: String) : Result()
data object Loading : Result()
}
fun render(r: Result): String = when (r) {
is Result.Success -> "Showing: ${r.data}"
is Result.Error -> "Error ${r.code}: ${r.message}"
Result.Loading -> "Spinner..."
}
fun main() {
println(render(Result.Loading))
println(render(Result.Success("3 new messages")))
println(render(Result.Error(503, "Service unavailable")))
}Spinner...
Showing: 3 new messages
Error 503: Service unavailable
Notice:
- The
whenhas noelse: the compiler knowsSuccess,ErrorandLoadingare the only possibilities. - Inside each branch the value is smart-cast, so
r.dataandr.codeare available. Loadinghas no data, so it is adata object— a singleton with a nicetoString().
The compiler catches missing cases
Forget a case and the code no longer compiles — exactly what you want when you add a new state months later:
sealed interface Shape
class Circle(val r: Double) : Shape
class Square(val side: Double) : Shape
class Triangle(val b: Double, val h: Double) : Shape
fun area(s: Shape): Double = when (s) {
is Circle -> 3.14 * s.r * s.r
is Square -> s.side * s.side
}
fun main() {
println(area(Square(2.0)))
}File.kt:6:30: error: 'when' expression must be exhaustive. Add the 'is Triangle' branch or an 'else' branch.
Sealed interfaces
Since Kotlin 1.5, interfaces can be sealed too. A class can implement several sealed interfaces, which is handy for modelling events or commands:
sealed interface Command
data class Move(val dx: Int, val dy: Int) : Command
data class Say(val text: String) : Command
data object Quit : Command
fun main() {
val script = listOf(Move(1, 0), Say("hi"), Move(0, 2), Quit, Say("never"))
var x = 0
var y = 0
for (cmd in script) {
when (cmd) {
is Move -> { x += cmd.dx; y += cmd.dy }
is Say -> println("Robot says: ${cmd.text}")
Quit -> { println("Stopping at ($x, $y)"); break }
}
}
}Robot says: hi
Stopping at (1, 2)
Modelling UI state
A very common pattern in Android apps is a sealed hierarchy describing what a screen should show:
sealed class ProfileState {
data object Loading : ProfileState()
data class Loaded(val name: String, val followers: Int) : ProfileState()
data class Failed(val reason: String) : ProfileState()
}
fun headline(state: ProfileState) = when (state) {
ProfileState.Loading -> "Loading profile..."
is ProfileState.Loaded -> "${state.name} (${state.followers} followers)"
is ProfileState.Failed -> "Could not load: ${state.reason}"
}
fun main() {
val states = listOf(
ProfileState.Loading,
ProfileState.Loaded("Kai", 1280),
ProfileState.Failed("offline")
)
states.forEach { println(headline(it)) }
println(states[0])
}Loading profile...
Kai (1280 followers)
Could not load: offline
Loading
Rules for sealed classes
- A sealed class is abstract: you can't instantiate it directly.
- Its constructors are
protectedorprivate. - Direct subclasses must be in the same package and module (usually the same file).
- Subclasses themselves may be
data class,object, regular classes or even sealed again.
Tip: Use sealed types whenever you find yourself writing a class with a
type: Stringfield plus nullable fields that are only set "for some types". Each type becomes its own subclass with exactly the fields it needs.
Test yourself
What is the main advantage of a sealed class in a when expression?
- It runs faster
- The compiler knows all subclasses, so
elseisn't needed and missing cases are errors - It allows fall-through
- It converts to strings
How does a sealed class differ from an enum?
- Sealed classes can't be used in when
- Each sealed subclass can have its own properties and many instances
- Enums can have more cases
- They are identical
What is a good choice for a sealed case that carries no data, like Loading?
- data class Loading()
- data object Loading
- enum Loading
- val Loading = null