🚀 Enrollments Open for Jetpack Compose Cohort 3 — 4 Weeks of Live Learning to Build Modern Android UIs 💚Join Now
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

  1. State Management: Representing UI states (Loading, Success, Error).
  2. Result Wrapper: Handling API responses (Success, Failure).
  3. 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() } ```

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

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

Limited slots available each month

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚