Questions
KotlinIntermediate4 min
When to use Kotlin sealed classes?
Answer
Use Sealed Classes when you have a restricted class hierarchy where a value can have one of a limited set of types.
Use Cases
- State Management: Representing UI states (Loading, Success, Error).
- Result Wrapper: Handling API responses (Success, Failure).
- Event Handling: Defining a fixed set of user actions.
Benefits
- Exhaustive `when`: The compiler forces you to handle all subclasses in a `when` expression, ensuring type safety.
- Data Carrying: Unlike Enums, sealed class instances can hold different data.
```kotlin sealed class UiState { object Loading : UiState() data class Success(val data: String) : UiState() data class Error(val message: String) : UiState() } ```
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚