Sealed classes, enums and when
Why it matters
- UI state, navigation events, and domain models in Android are almost always modelled as sealed hierarchies; a catch-all
elsein awhenturns 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
whenis exhaustive and what happens when you add a new sub-type. - Choosing
enumvssealed classvssealed interfacechanges 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
enumis 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 interfaceis 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. whenexhaustiveness 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.
| Feature | enum | sealed class | sealed interface |
|---|---|---|---|
| Cases | fixed named instances | classes, data classes or objects | classes, data classes or objects |
| Different data per case | no, same properties for every constant | yes | yes |
| Several instances of one case | no | yes (class sub-types) | yes (class sub-types) |
| Where sub-types live | n/a | same module and package | same module and package |
| Can have abstract members | yes | yes | yes |
| Can hold state in the parent | yes (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
whenover a sealed type is exhaustive when every direct sub-type has a branch: noelseneeded. - Since Kotlin 1.7, non-exhaustive
whenstatements over sealed, enum, orBooleansubjects are a compile error, not just expressions. - An
enumconstant 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 interfacelets a sub-type extend another class or belong to several sealed hierarchies. The parent cannot hold state. - Inside a
whenbranch withis, the compiler smart-casts the subject when it is stable: a localval, a localvarnot modified between the check and the use, or avalproperty 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
whenwithoutelseover the parent fails to compile until you add a branch. This is the safety guarantee. whencan combine conditions with commas:when (x) { is A, is B -> ...; else -> ... }. Ranges work on values:in 1..10 -> ....- An
objectcase is matched withoutis:UiState.Loading ->compares to the single instance.is UiState.Loading ->also works. - At the bytecode level, an
enumcompiles to a class extendingjava.lang.Enumwith a static field per constant. Asealed classcompiles to an abstract class with a non-public constructor. Exhaustiveness is checked by the Kotlin compiler, and an exhaustivewhengets a hidden fallback that throwsNoWhenBranchMatchedException. - Do not use
elseas a catch-all for sealedwhenexpressions. 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
}UiStateis asealed 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 plainobject, but with a readabletoString()("Loading") and anequalsthat also holds for extra instances created by serialization.- The
whenoverUiStatehas noelse; the compiler guarantees all three branches are covered. Adding a fourth sub-type breaks compilation here. Destinationis anenumbecause the set of routes is fixed and every constant has the same shape: oneroutestring.
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
- A new
DeepLinksub-type was added to a sealedNavEventhierarchy, but awhenin the router used anelse -> Unitcatch-all. - Users who opened the new deep link landed on a blank screen because the
elsesilently swallowed the event. - Crash dashboards showed no error; the bug was invisible until a user reported it.
- Reproduce with a unit test that sends a
DeepLinkevent to the router and asserts a navigation happens. It fails before the fix. - Remove the
elsebranch, making thewhenexhaustive over the sealed type, and add theDeepLinkbranch the compiler now asks for. - Add a code-review rule (or a custom lint check) against
elsein awhenover a sealed type, so the next new sub-type forces every router to handle it at compile time.
- A
PaymentMethodenum had constantsCard,Wallet,Cryptowith no data fields. - The team needed to attach a
cardTokentoCardand awalletIdtoWallet. Enum constants are singletons, so they passed a nullableMapof extras alongside the enum everywhere. - Type safety was lost; a
Cardpayment could carry awalletIdat runtime, and a missingcardTokenwas only found when the payment API rejected the request.
- Replace the enum with a
sealed interface PaymentMethodanddata classsub-types, each carrying its own required fields (data objectfor a case without data). - The
whenin the billing service stays exhaustive and becomes type-safe: each branch smart-casts to the right sub-type. - No more nullable maps; a
Cardcannot be created without acardToken.
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
Cardneeds a token andWalletneeds an ID, use asealed interfacewith separatedata classsub-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")throwsIllegalArgumentExceptionfor any name that is not a constant, including a new value the server added later. UseStatus.entries.firstOrNull { it.name == raw }with a fallback. - Comparing enum constants by their name string. Use
when (color) { Color.RED -> ... }orcolor == Color.RED. Comparingcolor.name == "RED"is fragile, case-sensitive, and breaks on renaming. - Branching on a mutable property and expecting a smart cast.
when (viewModel.state)withis Success ->does not smart-cast ifstateis avaror 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)
- Create a
sealed interface ChatMessagewith three sub-types:Text(val body: String),Image(val url: String), andNotice(val level: ChatLevel). - Write a
fun render(msg: ChatMessage): Stringthat uses awhenexpression with noelsebranch. Each branch returns a short label. - Add an
enum class ChatLevel(val label: String)with constantsINFO("info"),WARN("warn"),ERROR("error"). - Write a
fun levelName(l: ChatLevel): Stringusing awhenover the enum. Noelse. - In
main(), create one of eachChatMessagesub-type and print the rendered string. Also printlevelNamefor each entry inChatLevel.entries. - Add a fourth sub-type
Video(val url: String)toChatMessage. Confirm thatrendernow fails to compile. Add the missing branch and print aVideomessage 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.