Sealed Classes in Kotlin
1 min read

Sealed Classes in Kotlin

Sealed Classes in Kotlin
Photo by Louis Tsai / Unsplash
Kotlin sealed classes are a powerful tool for creating restricted class hierarchies in which an object can only have one of the specified types. They are similar to Enums, but with additional features.

Implementing Kotlin Sealed Classes

A sealed class is defined by using the sealed keyword before the class declaration. When a class is declared as sealed, all of its subclasses must be defined in the same module as the sealed class. This means that the compiler knows the set of possible subclasses at compile time, allowing it to perform more advanced type-checking.

The same is true for sealed interfaces and their implementations: no new implementations can appear after a module with a sealed interface has been compiled.

Common use cases include implementing a State Machine or Functional Programming

A simple example of this would be representing the different types of vehicles:

sealed class Vehicle {
    class Car: Vehicle()
    class Truck: Vehicle()
    class Motorcycle: Vehicle()
}

Another example of a sealed class representing a state machine. it is done by creating a sealed class for each state and then creating subclasses for each possible transition between states.

sealed class State {
    class Initial: State()
    class Loading: State()
    class Success: State()
    class Error: State()
}

Sealed classes and when expression

The key benefit of using sealed classes comes into play when you use them in  when expression, which allows you to match against all possible subtypes of a sealed class in a concise and readable way. This can be used to handle each state in the state machine example above:

fun handleState(state: State) {
    when(state) {
        is State.Initial -> print("Initial state")
        is State.Loading -> print("Loading state")
        is State.Success -> print("Success state")
        is State.Error -> print("Error state")
        // the `else` clause is not required because all the cases are covered
    }
}

Conclusion

In conclusion, Kotlin sealed classes are a great tool for creating restricted class hierarchies, representing closed sets of options and handling state machines, they provide a more powerful and expressive alternative to enums, and they can help you write safer and more maintainable code.