Sealed Classes in Kotlin
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 use case for sealed classes is to represent a state machine. This 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")
}
}
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.
Subscribe to my newsletter
Read articles from Nitish Bhatt directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by