Intermediate 7 min readKotlin 2.0
Kotlin Sealed Classes โ Restricted Class Hierarchies
A sealed class is a class with a fixed set of subclasses defined in the same package. This lets the compiler enforce exhaustive when expressions.
What You Will Learn
- Declare sealed classes and their subclasses
- Use sealed classes in when expressions
- Model UI state with sealed classes
- Difference between sealed class and enum
Declaring Sealed Classes
Use the sealed modifier. All direct subclasses must be in the same package.
Sealed Class for Result
kotlin
sealed class Result<out T>
data class Success<T>(val data: T) : Result<T>()
data class Error(val message: String) : Result<Nothing>()
object Loading : Result<Nothing>()
fun handle(result: Result<String>) {
when (result) {
is Success -> println("Data: ${result.data}")
is Error -> println("Error: ${result.message}")
Loading -> println("Loading...")
}
}
fun main() {
handle(Success("Hello Kotlin"))
handle(Error("Network timeout"))
handle(Loading)
}Output
Data: Hello Kotlin
Error: Network timeout
Loading...
when is exhaustive โ no else needed because the compiler knows all subclasses. is checks the type. Smart cast gives access to subclass properties.
Best Practice: Use sealed classes to model UI state: Loading, Success, Error. Use sealed interfaces for Kotlin 1.5+ (more flexible).
Sealed Class vs Enum
Both restrict the set of values, but sealed classes are more powerful.
Sealed vs Enum
kotlin
// Enum โ each constant is the same type
enum class Direction { NORTH, SOUTH, EAST, WEST }
// Sealed โ each subclass can have different properties
sealed class Event
data class Click(val x: Int, val y: Int) : Event()
data class KeyPress(val key: String) : Event()
object Dismiss : Event()
fun main() {
val event: Event = Click(100, 200)
when (event) {
is Click -> println("Click at (${event.x}, ${event.y})")
is KeyPress -> println("Key: ${event.key}")
Dismiss -> println("Dismissed")
}
}Output
Click at (100, 200)
Sealed class subclasses can hold different data. Enum constants cannot. Use enums for simple sets of constants; sealed classes for types with distinct data.
Practice Exercise
Exercisemultiple choice
What advantage does a sealed class give in a when expression?
Quick Quiz
Quick Quiz
Where must sealed class subclasses be defined in Kotlin?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review