Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Kotlin
Kotlinmedium

`sealed class` vs `enum` — when would you choose `sealed`?

Tags
#sealed#enum#when
Back to categoryPractice quiz

Answer

Use `sealed` when you need a closed set of variants that can carry different data and types (sum type). It enables exhaustive `when` checks, while `enum` is a fixed set of instances of one type.

sealed interface Result

data class Ok(val value: Int) : Result

data class Err(val message: String) : Result

fun handle(r: Result) = when (r) {
  is Ok -> r.value
  is Err -> 0
}

Advanced answer

Deep dive

Use `enum` when you need a small fixed set of constants of one type (singletons).

Use `sealed` when variants can have different shapes/data:

  • `sealed interface Result { data class Ok(val v: Int): Result; data class Err(val msg: String): Result }`

Benefits of `sealed`:

  • Exhaustive `when` (compiler can force handling all cases).
  • Each variant can carry different fields and behavior.

Common pitfalls

  • Using enums to model cases that need payload (you end up with nullable fields / awkward state).
  • Forgetting that sealed is “closed”: subclasses must be in the same package/module (depending on Kotlin version).

Related questions

Kotlin
`when` as an expression: what does it mean that it is exhaustive?
#kotlin#when#sealed
Kotlin
Sealed classes vs enums in Kotlin?
#sealed-class#enum#when
Java
What are sealed classes in Java and why use them?
#java#sealed#inheritance