TExcelTAD
Home › Kotlin › Kotlin Sealed Classes

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

kotlin · try it yourself
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 when has no else: the compiler knows Success, Error and Loading are the only possibilities.
  • Inside each branch the value is smart-cast, so r.data and r.code are available.
  • Loading has no data, so it is a data object — a singleton with a nice toString().

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:

kotlin · try it yourself
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:

kotlin · try it yourself
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:

kotlin · try it yourself
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 protected or private.
  • 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: String field 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?

  1. It runs faster
  2. The compiler knows all subclasses, so else isn't needed and missing cases are errors
  3. It allows fall-through
  4. It converts to strings

How does a sealed class differ from an enum?

  1. Sealed classes can't be used in when
  2. Each sealed subclass can have its own properties and many instances
  3. Enums can have more cases
  4. They are identical

What is a good choice for a sealed case that carries no data, like Loading?

  1. data class Loading()
  2. data object Loading
  3. enum Loading
  4. val Loading = null