1. Enum and sealed: when and why
If programming were a kitchen, then enum is a set of spice jars where each jar has a single word on it: SALT, PEPPER, PAPRIKA. And a sealed class is already a set of containers where one container can be “vegetable soup”, another “noodle soup”, a third “an empty pot (error: you forgot to turn on the stove)”. And each container has its own contents.
An enum class answers the question “which option is selected?” very well. But sometimes that is not enough: you want different options to carry different data. For example, when executing a command in an application:
- on success you want to return, say, the created expense id and a confirmation text;
- on error, the reason, possibly the problematic field, possibly a hint for the user.
If you try to do this via an enum, you will very quickly end up with a construction like “the enum has a bunch of fields, half of which are always null”, and that is exactly the kind of code smell that (like the smell of burnt wiring) is better caught early.
Technically, Kotlin allows modeling this via a sealed class: you define a base type “Operation result”, and then explicitly list the allowed variant types: for example Ok and Error.
Enum vs sealed: a quick cheat sheet
| Situation | Better: enum class | Better: sealed class |
|---|---|---|
| Options are just values from a list | Yes | Possible, but overkill |
| Each option has its own data | Usually inconvenient | Yes, that is the direct purpose |
| We want “success / error” with details | You can do it “head-on”, but it is often messy | Yes, an ideal case |
| We want to guarantee that no variants appear “from the side” | Partially | Yes, a closed family |
| Variants have the same shape | Yes | Not required |
And now an important practical thought: sealed is not “advanced for the sake of being advanced”. It is a way to make the program tell the truth with types. If an operation can end in success or error, then the result type should reflect that.
2. The main sealed idea: a closed family of types
Before writing code, it is important to understand what sealed means in plain language. The key idea: a sealed class defines a closed family of types. That is, you tell the compiler: “Here is the base type, and here is the list of variants, and there must be no other variants in this family (at least not suddenly somewhere else in the project)”.
Historically and conceptually, sealed types were invented so the compiler could “understand” the exhaustiveness of branching by variants. The Kotlin specification discusses this directly: sealed hierarchies are needed so that when can be exhaustive, because the compiler knows the full set of subclasses.
But in this lecture we will not dive deeply into handling variants via is and an exhaustive when — that is the next lecture. Today our task is simpler and more practical: learn to create a sealed model and return it from functions so you can stop using “magic strings”, null, and non-obvious flags.
3. Minimal example: Ok and Error
Now we will write the smallest possible sealed result. I will deliberately make the variants simple and short so you do not drown in details.
Pay attention to one practical trick: you can keep the variants “inside” the sealed class. Then the names Ok and Error do not clutter the whole project, and at the usage site it is immediately clear which family they belong to.
sealed class CommandResult {
data class Ok(val message: String) : CommandResult()
data class Error(val reason: String) : CommandResult()
}
There are a few important points here.
First, CommandResult is the base type. We usually do not create instances of it directly. We create variants: CommandResult.Ok(...) or CommandResult.Error(...).
Second, the variants are ordinary classes. And very often it is convenient to make them data class because they truly “hold data”. Kotlin explicitly allows a data class to extend other classes, including sealed ones (while the data class itself cannot be sealed).
4. Example from a CLI expense tracker
From here we will start tying the examples into a single application. Let’s say we have a simple console expense tracker (a familiar and pretty relatable idea: money disappears faster than lines of code—especially if you write lines of code in a coffee shop).
Suppose we already have an expense model and categories (it is convenient to store the category as an enum—this is exactly a “fixed set of values”).
enum class Category {
FOOD, TRANSPORT, OTHER
}
data class Expense(
val id: Int,
val title: String,
val amount: Double,
val category: Category
)
Now imagine the add command: the user enters a title, amount, and category, and we must either add the expense or explain why it did not work.
Why returning just a String is bad
A typical “first” approach looks like this: the function returns the text that we print.
The problem is that a string does not carry a strict meaning. A string can be either success or error—external code has to “guess” from the content.
And then you end up with something like this:
- "OK: added" — success
- "ERROR: invalid amount" — error
And suddenly you start parsing your own strings. That is like writing “Food inside” on a box, and then trying to figure out by smell whether it is food or batteries.
Sealed result for the add command
Let’s make the result a bit richer: on success we will store expenseId, and on error—a clear reason.
sealed class AddExpenseResult
data class AddOk(val expenseId: Int, val message: String) : AddExpenseResult()
data class AddError(val reason: String) : AddExpenseResult()
Yes, the names are a bit longer here. But that “longer” buys you clarity: you physically cannot confuse success and error.
5. Returning sealed from a function: error as a normal outcome
Now comes an important psychological moment for beginners. An error is not necessarily an exception. Very often, an error is just an expected outcome of an operation: the user can enter nonsense, a file can be missing, the amount can be negative. This is not a “catastrophe”, it is just a scenario branch.
That is exactly why a sealed result fits great: we return a value that says “here is what happened”.
Let’s make an expense-adding function. Let the storage be MutableList<Expense> (at this stage, that is fine).
fun addExpense(
expenses: MutableList<Expense>,
title: String,
amount: Double,
category: Category
): AddExpenseResult {
if (title.isBlank()) return AddError("Title must not be blank")
if (amount <= 0.0) return AddError("Amount must be greater than 0")
val newId = (expenses.maxOfOrNull { it.id } ?: 0) + 1
expenses.add(Expense(newId, title, amount, category))
return AddOk(expenseId = newId, message = "Expense added")
}
Notice how linearly the code reads: “checked → returned error → otherwise did the work → returned success”. This style is often called fail-fast: as soon as we understand that the operation is impossible, we immediately return a clear result.
6. A shared result for different commands
In the example above we created AddExpenseResult, but you will quickly notice: you will end up with RemoveExpenseResult, UpdateExpenseResult, ParseCommandResult, and so on.
And this is where you want a universal result “for commands in general”. A very common convention is the variants Ok and Error. It is good because in when (which we will cover next) the code reads like “if Ok—do one thing, if Error—do another”.
We already have such a type: CommandResult from the minimal example. Let’s use it.
fun addExpenseSimple(
expenses: MutableList<Expense>,
title: String,
amount: Double,
category: Category
): CommandResult {
if (title.isBlank()) return CommandResult.Error("Title must not be blank")
if (amount <= 0.0) return CommandResult.Error("Amount must be greater than 0")
val newId = (expenses.maxOfOrNull { it.id } ?: 0) + 1
expenses.add(Expense(newId, title, amount, category))
return CommandResult.Ok("Added: id=$newId")
}
What matters here is that we did not make the inheritance “deep” and complicated. Just two variants. But already the result type became honest.
7. A wider result shape: different data on success and error
Now let’s do what sealed is often chosen for: success and error have different “shapes” of data. For example:
- add success returns an Expense
- add error returns reason and badInput
Doing this cleanly with an enum is hard, but with sealed it is natural.
sealed class AddExpenseResult2
data class AddOk2(val expense: Expense) : AddExpenseResult2()
data class AddError2(val reason: String, val badInput: String) : AddExpenseResult2()
And the function:
fun addExpenseDetailed(
expenses: MutableList<Expense>,
title: String,
amountText: String,
category: Category
): AddExpenseResult2 {
val amount = amountText.toDoubleOrNull()
?: return AddError2("Amount must be a number", badInput = amountText)
if (amount <= 0.0) return AddError2("Amount must be greater than 0", badInput = amountText)
val newId = (expenses.maxOfOrNull { it.id } ?: 0) + 1
val expense = Expense(newId, title, amount, category)
expenses.add(expense)
return AddOk2(expense)
}
Notice how neatly we avoided null logic. We are not returning an Expense?, where null means “not added”. We return a value that explicitly says “which exact outcome happened”.
8. Where to keep variants and how the pipeline is structured
Where to declare variants
From the Kotlin rules point of view: a sealed hierarchy restricts where its subclasses can be located (in modern Kotlin versions—in the same module and package). For a beginner, the most practical advice is simpler: keep the base sealed class and its variants in one file while the project is small.
First, it is easier to read the code: you open the file and immediately see “what variants of the result exist at all”.
Second, there are fewer surprises: nobody will add “one more variant somewhere over there” and force you to search for it across the project.
You can think of it this way: a sealed class is like a folder of documents labeled “Inside only: passport, driver’s license, and certificate”. And you really want all of that to be in one folder, not scattered around the apartment.
Pipeline diagram: command → result
To avoid losing the big picture, it helps to see the process “command → logic → result” as a mini-pipeline.
flowchart TD
A[Vvod pol'zovatelya: stroka komandy] --> B[Parsing i validatsiya]
B -->|korrektno| C[Vypolnenie deystviya]
B -->|oshibka| E["Return Error(...)"]
C -->|uspekh| D["Return Ok(...)"]
sealed here is like a neat container for the output of steps B and C. Instead of “printing inside” or “throwing exceptions at every sneeze”, the function returns what happened, and the outer code decides what to do with it.
Sealed for errors and exceptions
Can you use sealed for exceptions? Yes: sealed can be a base for an error hierarchy (including exceptions) to make errors more structured.
But within our topic, it is important not to mix up the two approaches.
- When an error is an expected part of the scenario (invalid input, blank title, negative amount), it is often more convenient to return a sealed result.
- When an error is an unexpected breakdown (infrastructure failed, internal invariants were violated, “this must not happen”), then it is more often about exceptions.
Today we deliberately practice the first style: “error as a value”, but without Result<T> — purely with sealed class, so it is easier for you to feel the mechanics.
9. Typical mistakes when designing sealed results
Mistake #1: trying to cram everything into one class with a bunch of nullable fields.
Beginners often do something like class Result(val ok: Boolean, val message: String?, val reason: String?, val expense: Expense?). Formally it works, but the logic becomes implicit: which fields must be filled when ok=true? Which ones when ok=false? A sealed model solves this with types: in Ok you keep only what makes sense on success, and in Error— only what makes sense on error.
Mistake #2: “success” with an error inside.
Sometimes you see a variant like Ok(message = "ERROR: ..."). This breaks the meaning of the model: if you returned Ok, the outer code should be allowed to trust that everything is fine. If something went wrong, it must be an Error; otherwise the type stops being a contract and turns into decoration.
Mistake #3: inconsistency in variant names.
In one place Success/Failure, in another Good/Bad, in a third Ok/Error. The code reader (including you in two weeks) starts spending energy “switching dictionaries”. Pick one convention (in our course—Ok/Error) and stick to it; then result handling will look the same across the project.
Mistake #4: returning null instead of Error.
null is “no value”, but almost never “an explanation of the problem”. When you return null, you lose the reason and force the calling code to guess. A sealed error is good because it carries data: why it failed, what exactly was wrong, what to show the user.
Mistake #5: mixing command execution and console output.
It is very tempting to do println("Added!") inside addExpense(...). But then the function becomes inflexible: you cannot use it elsewhere (for example, in tests or in a different UI), and it is hard to control the output. It is better to return Ok/Error, and do printing outside—where you decide “how exactly do we show the result to the user”.
GO TO FULL VERSION