0
0
Kotlinprogramming~5 mins

Sealed classes for restricted hierarchies in Kotlin

Choose your learning style9 modes available
Introduction
Sealed classes help you group related types in one place and control which classes can extend them. This makes your code safer and easier to understand.
When you want to represent a fixed set of types, like different states of a process.
When you want the compiler to check that you handle all possible cases in a when expression.
When you want to restrict class inheritance to a known set of subclasses.
When modeling choices or options that don't change often.
When you want clearer and safer code for handling different types of results.
Syntax
Kotlin
sealed class Shape {
    class Circle(val radius: Double) : Shape()
    class Rectangle(val width: Double, val height: Double) : Shape()
}
A sealed class can only be subclassed inside the same file where it is declared.
You can use a sealed class with a when expression to cover all cases without needing an else branch.
Examples
Defines a sealed class Result with two possible subclasses: Success and Error.
Kotlin
sealed class Result {
    class Success(val data: String) : Result()
    class Error(val error: Throwable) : Result()
}
Using a when expression to handle all subclasses of the sealed class Result.
Kotlin
fun handleResult(result: Result) = when(result) {
    is Result.Success -> println("Data: ${result.data}")
    is Result.Error -> println("Error: ${result.error.message}")
}
Sample Program
This program defines a sealed class TrafficLight with three fixed states. The action function returns what to do for each light. The main function prints the action for Yellow light.
Kotlin
sealed class TrafficLight {
    object Red : TrafficLight()
    object Yellow : TrafficLight()
    object Green : TrafficLight()
}

fun action(light: TrafficLight) = when(light) {
    TrafficLight.Red -> "Stop"
    TrafficLight.Yellow -> "Get Ready"
    TrafficLight.Green -> "Go"
}

fun main() {
    val currentLight = TrafficLight.Yellow
    println(action(currentLight))
}
OutputSuccess
Important Notes
Sealed classes improve safety by letting the compiler check all possible subclasses are handled.
You can use objects as subclasses when you don't need to store data, just represent a single value.
All subclasses must be declared in the same file as the sealed class.
Summary
Sealed classes restrict which classes can extend them, all in one file.
They help you write safer code by forcing you to handle all cases.
Use sealed classes to model fixed sets of related types clearly and simply.