0
0
Kotlinprogramming~5 mins

Sealed classes with when exhaustive check in Kotlin

Choose your learning style9 modes available
Introduction

Sealed classes help group related types together. Using when with sealed classes ensures you handle all cases, making your code safer and clearer.

When you have a fixed set of related types and want to handle each type differently.
When you want the compiler to warn you if you forget to handle a case in a <code>when</code> expression.
When modeling states in an app, like loading, success, or error states.
When you want to avoid using many <code>if-else</code> checks and prefer a clear, structured approach.
Syntax
Kotlin
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: String) : Result()
    object Loading : Result()
}

fun handleResult(result: Result) {
    when (result) {
        is Result.Success -> println("Success: ${result.data}")
        is Result.Error -> println("Error: ${result.error}")
        Result.Loading -> println("Loading...")
    } // No else needed because all cases are covered
}

Sealed classes restrict subclassing to the same file, so the compiler knows all subclasses.

The when expression is exhaustive if it covers all subclasses, so no else branch is needed.

Examples
Simple sealed class with two objects and a when expression that covers both cases.
Kotlin
sealed class Shape {
    object Circle : Shape()
    object Square : Shape()
}

fun describe(shape: Shape) = when(shape) {
    Shape.Circle -> "This is a circle"
    Shape.Square -> "This is a square"
}
Sealed class with a data class and an object. The when handles both types without else.
Kotlin
sealed class Response {
    data class Success(val message: String) : Response()
    object Failure : Response()
}

fun printResponse(response: Response) {
    when(response) {
        is Response.Success -> println("Success: ${response.message}")
        Response.Failure -> println("Failure occurred")
    }
}
Sample Program

This program defines a sealed class TrafficLight with three states. The action function uses a when expression to return the correct action for each light. Because all cases are covered, no else is needed. The main function prints the action for the 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

If you add a new subclass to the sealed class, the compiler will warn you to update the when expression.

Sealed classes must be declared in the same file as their subclasses.

Using sealed classes with when helps avoid bugs by forcing you to handle all cases.

Summary

Sealed classes group related types and restrict subclassing to one file.

when expressions with sealed classes are exhaustive if all subclasses are handled.

This makes your code safer and easier to maintain.