Kotlin — Sealed Classes
Basic sealed class
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
object Loading : Result()
}
fun handle(result: Result) = when (result) {
is Result.Success -> println("Data: ${result.data}")
is Result.Error -> println("Error: ${result.message}")
is Result.Loading -> println("Loading...")
}
Sealed interface
sealed interface Shape {
data class Circle(val radius: Double) : Shape
data class Rectangle(val width: Double, val height: Double) : Shape
}
fun area(shape: Shape) = when (shape) {
is Shape.Circle -> Math.PI * shape.radius.pow(2)
is Shape.Rectangle -> shape.width * shape.height
}
Mini Practice
Write Kotlin code that:
- Creates a sealed class with data classes
- Uses when expression for exhaustive matching
- Creates a sealed interface
- Demonstrates exhaustive when
Up Next
In the next lesson, you'll learn about Inline Classes — type-safe wrappers.
Related Topics
Frequently Asked Questions about Sealed Classes
What is Sealed Classes in Kotlin?
Sealed Classes is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sealed Classes?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sealed Classes.
Why is Sealed Classes important in Kotlin?
Sealed Classes is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.