0
0
KotlinHow-ToBeginner · 4 min read

How to Use Sealed Class in Kotlin: Syntax and Examples

In Kotlin, a sealed class restricts class inheritance to a fixed set of subclasses defined in the same file, enabling exhaustive when expressions. Use sealed class to represent restricted hierarchies and improve type safety by handling all cases explicitly.
📐

Syntax

A sealed class is declared with the sealed keyword. Its subclasses must be defined in the same file, either as class, data class, or object. This setup allows the compiler to know all possible subclasses.

  • sealed class: The base class that restricts inheritance.
  • subclasses: Defined in the same file, they represent all possible types.
  • when expression: Can be exhaustive without an else branch because all subclasses are known.
kotlin
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: String) : Result()
    object Loading : Result()
}
💻

Example

This example shows how to define a sealed class Result with three subclasses and use a when expression to handle all cases safely.

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 with data: ${result.data}")
        is Result.Error -> println("Error occurred: ${result.error}")
        Result.Loading -> println("Loading...")
    }
}

fun main() {
    val success = Result.Success("File loaded")
    val error = Result.Error("Network failure")
    val loading = Result.Loading

    handleResult(success)
    handleResult(error)
    handleResult(loading)
}
Output
Success with data: File loaded Error occurred: Network failure Loading...
⚠️

Common Pitfalls

Common mistakes when using sealed classes include:

  • Defining subclasses outside the sealed class file, which is not allowed.
  • Forgetting to handle all subclasses in a when expression, which can cause compilation errors.
  • Using sealed interface when a sealed class is needed for shared state or implementation.

Always keep subclasses in the same file and handle all cases explicitly.

kotlin
sealed class Shape {
    class Circle(val radius: Double) : Shape()
    class Square(val side: Double) : Shape()
}

fun area(shape: Shape): Double {
    return when (shape) {
        is Shape.Circle -> 3.14 * shape.radius * shape.radius
        // Missing handling for Shape.Square causes error
        else -> throw IllegalArgumentException("Unknown shape")
    }
}
📊

Quick Reference

  • sealed class: Use to restrict subclassing to the same file.
  • Subclasses: Must be nested or in the same file.
  • when expression: Can be exhaustive without else.
  • Use cases: Represent restricted hierarchies like states or results.

Key Takeaways

Use sealed class to limit subclassing to a fixed set defined in the same file.
All subclasses of a sealed class must be declared in the same Kotlin file.
The compiler enforces exhaustive when expressions for sealed classes, improving safety.
Sealed classes are ideal for representing restricted hierarchies like states or results.
Always handle all subclasses explicitly to avoid compilation errors.