Sealed classes help group related types together. Using when with sealed classes ensures you handle all cases, making your code safer and clearer.
Sealed classes with when exhaustive check in 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.
when expression that covers both cases.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" }
when handles both types without else.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") } }
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.
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)) }
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.
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.