One Class every Android Developer should know about: Sealed Class
When building Android apps, there’s one class you can’t afford to overlook: Sealed Classes.
It is like a hammer in your toolbox. You can use it to build something creative or crack open eggs to make an omelette. I know who makes an omelette with a hammer, but you can. Never mind let’s talk about Sealed classes and leave cooking skills for another day.
A sealed class provides a hierarchy of classes that can be used to restrict choices at compile time. This means that no other classes can be created once compiled, providing a fixed set of subclasses. This can be incredibly useful for managing the state and ensuring type safety.
Example of Sealed Classes
Let’s take an example to understand this better. Suppose we have a sealed class for different UI states in an application:
In this example, the hierarchy of classes is fixed. It means no other classes can come under UiState other than Loading, Success, and Failure. We can use this specific class to manage changes in the API calling state.
Tracking API Call States with Kotlin Flow
Using Kotlin Flow, we can track the state of an API call:
val uiStateFlow: Flow<UiState> = flow {
emit(UiState.Loading)
try {
val result = apiCall()
emit(UiState.Success(result))
} catch (e: Exception) {
emit(UiState.Failure(e))
}
}
Enum Classes vs. Sealed Classes
Enum Classes: Enum classes also provide a restricted hierarchy of classes. However, there are key differences between Enum classes and Sealed classes.
Key Differences and When to Use Them
Customization:
- Sealed Classes: Allow for more customization. You can have a hierarchy of data classes, objects, and other classes within sealed classes. This flexibility is useful for complex state management and data handling.
- Enum Classes: Provide a more restricted hierarchy. They are ideal for representing a fixed set of constants without the need for additional properties or methods.
Trick to Remember:
- More customization needed? Use Sealed Classes.
- Need to restrict hierarchy? Use Enum Classes.
Example of Enum Classes
Here’s a simple example of an Enum class:
Using Sealed Classes with When Statements
Sealed classes can be effectively used with when statements for exhaustive checks:
Conclusion:
Sealed classes provide a structured and type-safe way to manage complex state hierarchies, making your code more readable and maintainable. By understanding when to use sealed classes versus enum classes, you can make more informed decisions that enhance your codebase.
Thank you for reading this blog! I hope you found it enjoyable and informative. If I’ve made any errors, please forgive me.
Your Captain (the Commute),
Hitesh