androidengineers.Book a session
โ† All interview 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

  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.
sealed class UiState {
    object Loading : UiState()
    data class Success(val data: String) : UiState()
    data class Error(val message: String) : UiState()
}

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising