Sealed classes, enums and when

Learn how to use Kotlin sealed classes, interfaces, and enums in Android to model UI states and ensure exhaustive when expressions for safer code. About 22 minutes.

Why it matters

  • UI state, navigation events, and domain models in Android are almost always modelled as sealed hierarchies; a catch-all else in a when turns a forgotten branch into a silent bug that ships to production.
  • Interviewers ask you to model a state machine or a result type and expect you to explain why when is exhaustive and what happens when you add a new sub-type.
  • Choosing enum vs sealed class vs sealed interface changes whether sub-types can carry different data, whether there can be several instances of a case, and what a sub-type may also extend.
  • Since Kotlin 1.5, sealed sub-types can live in different files of the same package and module; knowing the exact rule prevents "why can I not put the subclass in another module" confusion during code reviews.

The simple explanation

  • A sealed class is like a closed menu at a restaurant: the kitchen can only serve dishes from that list, and the waiter (your when) must handle every dish or the order fails.
  • An enum is a fixed set of buttons on a remote: TV, radio, off. Every button has the same shape, and there is exactly one of each.
  • A sealed interface is like a contract that says 'any device in this family must expose these ports', but each device can add its own extra ports and belong to other families too.
  • when exhaustiveness is the checklist at the end of a shift: if a new dish appears on the menu, the checklist is incomplete until you add a step for it.

A sealed class (or sealed interface) restricts where direct sub-types can be declared: in the same module and the same package (Kotlin 1.5+). The compiler knows the full set of direct sub-types, so a when over that type is exhaustive without an else branch. If you add a new sub-type later, every when over the parent that has no else fails to compile until you add a branch.

An enum class has a fixed set of named instances. Each constant can pass constructor arguments and override members, but every constant has the same type and there is only one instance of each. Like sealed types, enums get exhaustive when checks.

Featureenumsealed classsealed interface
Casesfixed named instancesclasses, data classes or objectsclasses, data classes or objects
Different data per caseno, same properties for every constantyesyes
Several instances of one casenoyes (class sub-types)yes (class sub-types)
Where sub-types liven/asame module and packagesame module and package
Can have abstract membersyesyesyes
Can hold state in the parentyes (constructor properties)yes (constructor)no (interfaces have no state)

when as an expression returns a value and must be exhaustive. Since Kotlin 1.7, a when statement over a sealed, enum, or Boolean subject must also be exhaustive; only statements over other types may skip cases. Use is for type checks; the compiler smart-casts the subject inside the branch. Separate several conditions in one branch with commas, such as is A, is B ->. A when expression over a non-sealed type needs an else branch or it does not compile.

Notes

  • Direct sealed sub-types must be in the same module and package as the parent (Kotlin 1.5+). They no longer need to be in the same file.
  • A when over a sealed type is exhaustive when every direct sub-type has a branch: no else needed.
  • Since Kotlin 1.7, non-exhaustive when statements over sealed, enum, or Boolean subjects are a compile error, not just expressions.
  • An enum constant can hold constructor arguments and override members, but all constants share the enum's type and properties. You cannot create new constants at runtime.
  • A sealed interface lets a sub-type extend another class or belong to several sealed hierarchies. The parent cannot hold state.
  • Inside a when branch with is, the compiler smart-casts the subject when it is stable: a local val, a local var not modified between the check and the use, or a val property without a custom getter declared in the same module. when (val s = state) is a handy way to get a stable subject.
  • If you add a new sub-type to a sealed hierarchy, every when without else over the parent fails to compile until you add a branch. This is the safety guarantee.
  • when can combine conditions with commas: when (x) { is A, is B -> ...; else -> ... }. Ranges work on values: in 1..10 -> ....
  • An object case is matched without is: UiState.Loading -> compares to the single instance. is UiState.Loading -> also works.
  • At the bytecode level, an enum compiles to a class extending java.lang.Enum with a static field per constant. A sealed class compiles to an abstract class with a non-public constructor. Exhaustiveness is checked by the Kotlin compiler, and an exhaustive when gets a hidden fallback that throws NoWhenBranchMatchedException.
  • Do not use else as a catch-all for sealed when expressions. It hides new sub-types and defeats the exhaustiveness check.

Code example

This shows a typical Android UI-state sealed hierarchy with an exhaustive when that renders a label for each state, plus an enum for a fixed set of navigation destinations.

// Sealed hierarchy for a screen's UI state
sealed interface UiState {
    data object Loading : UiState
    data class Success(val items: List<String>) : UiState
    data class Error(val message: String) : UiState
}
 
// Enum for a fixed set of navigation destinations
enum class Destination(val route: String) {
    Home("home"),
    Profile("profile"),
    Settings("settings")
}
 
// Exhaustive when: no else needed because UiState is sealed
fun render(state: UiState): String = when (state) {
    UiState.Loading -> "Loading..."
    is UiState.Success -> "Items: " + state.items.joinToString(", ")
    is UiState.Error -> "Error: " + state.message
}
 
// Exhaustive when over an enum: no else needed either
fun routeFor(dest: Destination): String = when (dest) {
    Destination.Home -> dest.route + "/feed"
    Destination.Profile -> dest.route + "/me"
    Destination.Settings -> dest.route + "/prefs"
}
 
fun main() {
    val s1 = UiState.Success(listOf("a", "b"))
    val s2 = UiState.Error("timeout")
    println(render(s1))           // Items: a, b
    println(render(s2))           // Error: timeout
    println(routeFor(Destination.Profile)) // profile/me
}
  • UiState is a sealed interface, so a sub-type could also extend another class or implement another sealed interface later.
  • data object Loading (stable since Kotlin 1.9) is a singleton like a plain object, but with a readable toString() ("Loading") and an equals that also holds for extra instances created by serialization.
  • The when over UiState has no else; the compiler guarantees all three branches are covered. Adding a fourth sub-type breaks compilation here.
  • Destination is an enum because the set of routes is fixed and every constant has the same shape: one route string.

Run the idea in plain Kotlin

sealed interface Shape {
  data class Circle(val radius: Double) : Shape
  data class Rect(val w: Double, val h: Double) : Shape
  data object Dot : Shape
}

enum class Color(val rgb: Int) {
  RED(0xFF0000),
  GREEN(0x00FF00),
  BLUE(0x0000FF)
}

fun describe(s: Shape): String = when (s) {
  is Shape.Circle -> "Circle r=" + s.radius
  is Shape.Rect -> "Rect " + s.w + "x" + s.h
  Shape.Dot -> "Dot"
}

fun colorName(c: Color): String = when (c) {
  Color.RED -> "red"
  Color.GREEN -> "green"
  Color.BLUE -> "blue"
}

fun main() {
  val shapes: List<Shape> = listOf(
      Shape.Circle(3.0),
      Shape.Rect(4.0, 5.0),
      Shape.Dot
  )
  for (s in shapes) {
      println(describe(s))
  }
  println("---")
  for (c in Color.entries) {
      println(colorName(c) + " rgb=" + c.rgb)
  }
}

The playground prints Circle r=3.0, Rect 4.0x5.0, Dot, a --- separator, then red rgb=16711680, green rgb=65280 and blue rgb=255.

In production

Missing branch in a navigation event handler
  • A new DeepLink sub-type was added to a sealed NavEvent hierarchy, but a when in the router used an else -> Unit catch-all.
  • Users who opened the new deep link landed on a blank screen because the else silently swallowed the event.
  • Crash dashboards showed no error; the bug was invisible until a user reported it.
The fix
  • Reproduce with a unit test that sends a DeepLink event to the router and asserts a navigation happens. It fails before the fix.
  • Remove the else branch, making the when exhaustive over the sealed type, and add the DeepLink branch the compiler now asks for.
  • Add a code-review rule (or a custom lint check) against else in a when over a sealed type, so the next new sub-type forces every router to handle it at compile time.
Enum used where a sealed class was needed
  • A PaymentMethod enum had constants Card, Wallet, Crypto with no data fields.
  • The team needed to attach a cardToken to Card and a walletId to Wallet. Enum constants are singletons, so they passed a nullable Map of extras alongside the enum everywhere.
  • Type safety was lost; a Card payment could carry a walletId at runtime, and a missing cardToken was only found when the payment API rejected the request.
The fix
  • Replace the enum with a sealed interface PaymentMethod and data class sub-types, each carrying its own required fields (data object for a case without data).
  • The when in the billing service stays exhaustive and becomes type-safe: each branch smart-casts to the right sub-type.
  • No more nullable maps; a Card cannot be created without a cardToken.

Common mistakes

  • Adding else to a when over a sealed type. It hides new sub-types and defeats the compiler's exhaustiveness check. Remove else; let the compiler force you to handle every branch.
  • Using enum when cases need to carry different data. An enum constant can hold constructor arguments, but all constants share the same properties and there is only one instance of each. If Card needs a token and Wallet needs an ID, use a sealed interface with separate data class sub-types.
  • Putting a sealed sub-type in a different package or module. Direct sub-types must be in the same module and package as the parent. Moving one elsewhere is a compile error. Keep the whole hierarchy together.
  • Parsing server values with valueOf. Status.valueOf("archived") throws IllegalArgumentException for any name that is not a constant, including a new value the server added later. Use Status.entries.firstOrNull { it.name == raw } with a fallback.
  • Comparing enum constants by their name string. Use when (color) { Color.RED -> ... } or color == Color.RED. Comparing color.name == "RED" is fragile, case-sensitive, and breaks on renaming.
  • Branching on a mutable property and expecting a smart cast. when (viewModel.state) with is Success -> does not smart-cast if state is a var or has a custom getter. Capture it first: when (val s = viewModel.state).

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a sealed class and an enum in Kotlin?”

“Why is a when expression over a sealed type exhaustive without an else branch?”

“When would you choose a sealed interface over a sealed class?”

“What happens if you add a new sub-type to a sealed hierarchy and forget to update a when?”

Quiz

Which of the following is true about a when expression over a sealed class?

What is the main difference between an enum class and a sealed class?

Where must direct sub-types of a sealed class be declared in Kotlin 2.x?

You add a new sub-type to a sealed hierarchy. A when expression over the parent has a branch for each old sub-type and no else. What happens?

0 of 4 answered

Mini task

Exercise: Model a chat message type (15 min)

  1. Create a sealed interface ChatMessage with three sub-types: Text(val body: String), Image(val url: String), and Notice(val level: ChatLevel).
  2. Write a fun render(msg: ChatMessage): String that uses a when expression with no else branch. Each branch returns a short label.
  3. Add an enum class ChatLevel(val label: String) with constants INFO("info"), WARN("warn"), ERROR("error").
  4. Write a fun levelName(l: ChatLevel): String using a when over the enum. No else.
  5. In main(), create one of each ChatMessage sub-type and print the rendered string. Also print levelName for each entry in ChatLevel.entries.
  6. Add a fourth sub-type Video(val url: String) to ChatMessage. Confirm that render now fails to compile. Add the missing branch and print a Video message too.

Done condition: All code compiles. The when in render has no else. Adding Video without updating render produces a compile error. The program prints four lines for the messages and three lines for the levels.

Next: Collections and sequences