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.
sealed class Shape { class Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() }
sealed class Result { class Success(val data: String) : Result() class Error(val error: Throwable) : Result() }
fun handleResult(result: Result) = when(result) { is Result.Success -> println("Data: ${result.data}") is Result.Error -> println("Error: ${result.error.message}") }
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)) }
sealed classes in Kotlin?Shape in Kotlin?sealed class followed by the name and body.open and sealed. sealed interface Shape {} uses sealed interface which is invalid. abstract sealed class Shape {} wrongly combines abstract and sealed.sealed class Result {
data class Success(val data: String) : Result()
object Failure : Result()
}
fun handle(result: Result) = when(result) {
is Result.Success -> "Data: ${result.data}"
is Result.Failure -> "Failed"
}
println(handle(Result.Success("OK")))Result has two subclasses: Success and Failure. The when expression covers both cases without else.Result.Success("OK"), so the first branch matches, returning "Data: OK".sealed class Animal class Dog : Animal() class Cat : Animal()
Admin, Guest, and Member. Which approach correctly uses sealed classes to restrict roles and safely handle all cases?when expression covers all subclasses without else, ensuring safe handling.Pass the test and this pattern moves unknown