Sealed Class (Kotlin)

A sealed class defines a restricted hierarchy where all direct subclasses are known at compile time. This lets when expressions over it be exhaustive without an else branch.

Kotlin

Marking a class sealed means it can only be subclassed within the same module/package, so the compiler knows the complete set of subtypes. This is ideal for modeling a fixed set of states or outcomes — a Result that is either Success or Error, a UI state that is Loading, Content, or Empty.

The big payoff is exhaustive when: because every subclass is known, a when over a sealed type that handles each subtype needs no else, and adding a new subtype later turns every such when into a compile error until you handle it. That makes refactoring safe.

Sealed classes are like enums whose 'cases' can carry different data and even be different classes. Use a sealed interface for the same exhaustiveness when you need multiple-inheritance-style flexibility.

Syntax

sealed class Result
data class Ok(val data: String) : Result()
data class Err(val msg: String) : Result()

Examples

Kotlin

sealed class Shape
class Circle(val r: Double) : Shape()
class Square(val s: Double) : Shape()

fun area(shape: Shape): Double = when (shape) {
    is Circle -> 3.14 * shape.r * shape.r
    is Square -> shape.s * shape.s
}
println(area(Square(4.0)))

Output:

16.0

Learn it in a lesson

See also

Back to the Dictionary