Skip to content
tezvyn:

When would you use a sealed class instead of an enum?

Source: kotlinlang.orgHardHow cards are made

When would you use a sealed class instead of an enum?

This tests closed hierarchies versus singleton constants. A strong answer contrasts enums with sealed class instances, shows a NetworkResult example with data-bearing branches, and highlights exhaustiveness.

What's really being asked

This question evaluates whether you understand the difference between a set of singleton constants and a closed type hierarchy where each subtype can carry its own state. Interviewers want to see that you know sealed classes provide compile-time exhaustiveness with when expressions while allowing heterogeneous data shapes, something enums cannot do cleanly.

The full answer

First, the structural distinction: enum entries are singleton objects that all share the exact same constructor and properties, so every constant must carry the same fields even when they are irrelevant. Second, the sealed class advantage: each direct subclass can declare its own constructor parameters, so Success can hold a data payload and Error can hold a message and throwable while Loading needs nothing. Third, the when exhaustiveness guarantee: because all direct subclasses of a sealed class are known at compile time within the same module and package, a when expression used as a statement does not need an else branch; if you later add a new subclass, the compiler flags every incomplete when. Fourth, mention that sealed classes are abstract and cannot be instantiated directly, which enforces the hierarchy boundary.

The mistakes people make

Saying that enums are fine because they can have abstract methods or properties misses the point that every enum constant still conforms to one uniform signature. Suggesting that data classes alone solve the problem ignores the closed hierarchy guarantee that prevents external code from creating new states that your when expressions do not handle. Another red flag is conflating sealed classes with sealed interfaces without explaining that both restrict the hierarchy but classes carry state more naturally for this use case.

What usually comes next

The interviewer may ask how sealed classes interact with modules and visibility, specifically that no new subclasses can appear outside the module where the sealed class is defined. They might also ask how this compares to sealed interfaces in Java 15 or when to prefer a sealed interface over a sealed class. You could also be asked about serialization implications or how to handle state in ViewModels using sealed classes with Flow or LiveData.

A concrete example

Imagine a network request represented by a sealed class called NetworkResult. Inside it, define object Loading to represent an in-flight request with no data. Define data class Success with a val data String to hold the response payload. Define data class Error with a val message String to hold the failure reason. In your UI rendering function, write a when statement over a NetworkResult parameter. In the Loading branch, show a progress indicator. In the Success branch, display the data string. In the Error branch, show the message string. Because NetworkResult is sealed, Kotlin verifies at compile time that these three branches cover every possibility. If you later add a Cancelled subclass inside the same package, every when expression using NetworkResult breaks the build until you handle the new state, which is exactly the safety sealed classes are designed to provide.

Interview question

When modeling a closed set of UI states where Loading needs no data, Success carries a User, and Error carries a String, why is a sealed class preferable to an enum?

  • a.Enums cannot implement interfaces or hold properties, limiting them to simple constant values
  • b.Enum constants share a single constructor signature, making it awkward to attach different data to each state, whereas sealed subclasses can define their own parametersCorrect
  • c.A plain data class hierarchy solves the same problem more simply, since sealed classes add unnecessary restrictions on inheritance
  • d.Sealed classes guarantee that when expressions do not need an else branch, while enum-based when expressions always require one
Why?

The correct answer captures the core structural distinction: enums force all constants into one uniform signature, while sealed subclasses can each carry heterogeneous state. Option C is tempting because data classes appear to model payloads well, but without the sealed modifier the hierarchy is open, so when expressions lose compile-time exhaustiveness and external code could add unhandled states.

Just read this? Test yourself on what you have been reading.

Read the original → kotlinlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on kotlin — each one lists the topics its interview covers.

See open roles