1. Introduction
Honestly, println() is a very tempting thing. You write it once, you see “Hooray, it worked” in the console, and it feels like life is good. The problem is that after a few functions and a couple of if branches, your code starts to look like a chat with yourself: somewhere we print success, somewhere an error, somewhere we print “almost success,” and somewhere we silently print nothing. This becomes hard to test and hard to extend.
Imagine our console learning project (we’ve been evolving it for a long time): a simple expense tracker. We have Expense (an expense object), a list of expenses in MutableList, commands like add, list, remove. At some point a question comes up: how should a function report its result?
| Approach | How it looks | What’s wrong |
|---|---|---|
| Print inside the function | |
The function “both computes and talks.” Hard to reuse and test. |
| Return String? | |
null does a poor job explaining what went wrong. And it’s easy to forget to check. |
| Return a sealed result Ok/Error | |
A bit more code, but a clear contract and strict handling. |
We take the third option: it disciplines both the code and the brain. And the brain is a moody thing—it’s better not to annoy it.
2. A single sealed result: Ok and Error
Now comes an important idea that sounds simpler than it feels in practice. We want any “command operation” in the app to return the same result type, so that handling is the same everywhere. Then in main we can write one nice when—and not smear printing across the whole project.
Let’s start with the minimum:
sealed class CommandResult
data class Ok(val message: String) : CommandResult()
data class Error(val reason: String) : CommandResult()
Here CommandResult is the base type, and Ok and Error are two variants (two concrete types) that inherit from it. In Kotlin, such sealed hierarchies pair well with an exhaustive when: the compiler knows the set of variants and helps you avoid forgetting a case.
Pay attention to the naming convention. We intentionally use Ok/Error everywhere, instead of jumping between Success/Fail, Good/Bad, Fine/Oops. It’s a small thing, but it makes reading code faster: your eyes get used to the fact that the result always has the same shape.
3. Business functions: return CommandResult
Now let’s “ground” the idea a bit in our expense tracker. Suppose Expense and Category already exist (we introduced them earlier, when we moved to classes and enum). For example, very simplified:
data class Expense(
val amount: Int,
val category: Category,
val comment: String
)
enum class Category { FOOD, TRANSPORT, OTHER }
Now we write a function that adds an expense. Important: it does not print. It returns a result.
fun addExpense(
expenses: MutableList<Expense>,
amount: Int,
category: Category,
comment: String
): CommandResult {
if (amount <= 0) return Error("Amount must be > 0")
expenses.add(Expense(amount, category, comment))
return Ok("Added expense: $amount in category ${category.name}")
}
Notice how linearly this reads: validate → if bad, return Error → otherwise add and return Ok. No “internal talking” via println(). We simply report the fact: success or error.
The same principle for removal. Suppose we remove by index:
fun removeExpense(expenses: MutableList<Expense>, index: Int): CommandResult {
if (index !in expenses.indices) return Error("No expense with index $index")
val removed = expenses.removeAt(index)
return Ok("Removed expense: ${removed.amount} (${removed.category.name})")
}
Notice a nice thing: we use the removal result to form the message. If we printed inside, printing would be “soldered” into the function. But this way we return the data (via a string) as part of the result contract.
4. when as a message dispatcher
The tastiest moment today is where sealed and when start working as a team.
We want one function that turns a command result into a user-facing string. Let’s call it render(...). And here we make when an expression: we return a string.
fun render(result: CommandResult): String =
when (result) {
is Ok -> "OK: ${result.message}"
is Error -> "ERROR: ${result.reason}"
}
Why this is great:
First, when here is specifically an expression, meaning it returns a value. Kotlin requires such a when to be exhaustive.
Second, for a sealed type you can make an exhaustive when without else, because all variants are known (in our case there are exactly two). This means: if tomorrow you add a third variant (for example, Help(...) or Empty(...)), the compiler will honestly say: “Hey, you forgot to handle the new type.”
That’s the “seat belt” we want to get for free from the compiler.
5. The loop in main: got → rendered → printed
Now let’s assemble a typical CLI app loop. We won’t complicate the command parser (you’ve already seen one earlier, when you learned to parse strings and write utility functions). The key here is to show the data flow.
First, a sketch of the loop:
fun main() {
val expenses = mutableListOf<Expense>()
while (true) {
print("> ")
val input = readln()
val result = handleCommand(expenses, input)
println(render(result))
}
}
Notice the beauty: main has become a “coordinator,” not a dumping ground for logic. It does only three things: reads a line, gets a result, prints a formatted message.
You can even draw a mini diagram to make it easier for the brain:
flowchart TD
A[readln: command string] --> B[handleCommand: logic]
B --> C[CommandResult: Ok/Error]
C --> D[render: user-facing string]
D --> E[println]
And this is very important: render separates “the internal truth of the program” from “how we talk to the user.” It’s a small architecture, but it saves you from big chaos.
6. Command handling and layer responsibilities
The command handler returns CommandResult
Now we’ll make the simplest handleCommand. Yes, it will be pretty “toy-like,” but what matters to us is the result contract.
Say we have commands:
- add <amount> <category> <comment...>
- list
- remove <index>
- exit
Here is a minimal handler (simplified parsing via split(), without quote support):
fun handleCommand(expenses: MutableList<Expense>, input: String): CommandResult {
val parts = input.trim().split(" ")
if (parts.isEmpty() || parts[0].isEmpty()) return Error("Empty command")
return when (parts[0].lowercase()) {
"list" -> listExpenses(expenses)
"exit" -> Ok("Exiting the program")
else -> Error("Unknown command: '${parts[0]}'")
}
}
Note: even for exit we return Ok for now. Why? Because within this lecture it’s important to show a unified result flow. Later you can make a special exit command and actually break the loop, but right now the Ok/Error logic matters more.
Let’s make listExpenses, which returns a multi-line message. We know StringBuilder (it was in the course earlier), so we’ll use it carefully:
fun listExpenses(expenses: List<Expense>): CommandResult {
if (expenses.isEmpty()) return Ok("The expense list is empty")
val sb = StringBuilder()
for (i in expenses.indices) {
val e = expenses[i]
sb.append("$i) ${e.amount} ${e.category.name} — ${e.comment}\n")
}
return Ok(sb.toString().trimEnd())
}
We return Ok even for an “empty list,” because that’s not an error—it’s a normal outcome of the operation. And this is important discipline: an error is when the command cannot be executed correctly, not when the result is “uninteresting.”
Principle: do vs. say
Here we arrive at a very practical principle: a function that performs an action should not simultaneously decide how exactly we will report it to the user. It’s like in a cafe: the chef cooks, the waiter says what was brought. If the chef walks into the dining room and starts explaining the sauce ingredients to every guest, the restaurant will quickly turn into a stand-up show.
In code it looks like this:
- addExpense(...) mutates the list and returns CommandResult.
- render(...) knows how to print Ok/Error nicely (and consistently).
- main decides when to print.
A very useful effect: you can change the message style (for example, remove OK:), and you won’t have to dig into every business function. It’s enough to change render.
Why else in when over a sealed type is a bad safety net
Now a bit provocative, but kindly: else in when over a sealed type often looks like “I don’t want to think.” Sometimes it’s needed, but in our pattern it’s more often harmful.
Compare:
fun render(result: CommandResult): String =
when (result) {
is Ok -> "OK: ${result.message}"
is Error -> "ERROR: ${result.reason}"
}
And the “just in case” version:
fun render(result: CommandResult): String =
when (result) {
is Ok -> "OK: ${result.message}"
else -> "Something happened..."
}
In the second case you’ve lost the main benefit: if a new result variant appears, the compiler will no longer force you to handle it. It will say: “Well, you have else, so you kind of covered everything.” But you didn’t actually cover anything—you just put on a band-aid.
And again: for a when expression, exhaustiveness is not a whim, it’s part of the language rules.
In our style we use that strictness as help, not as an obstacle.
Message separate from format
Sometimes there’s a temptation to do this: “let Ok store a fully ready string with OK: already included,” and Error with ERROR:. Technically you can, but then you’ll mix “result data” and “output formatting.” Today we keep the discipline:
- Ok.message is the semantic success message (without styling).
- Error.reason is the error reason (without styling).
- Styling (OK:, ERROR:) is only in render.
This keeps the code cleaner and lets you change formatting without touching the logic.
If you want to be even stricter, you can add a small helper function:
fun printResult(result: CommandResult) {
println(render(result))
}
And in main you’d have:
val result = handleCommand(expenses, input)
printResult(result)
A small thing, but readability sometimes rests on exactly such small things.
7. Typical mistakes
Mistake #1: adding else to a when over a sealed type “just in case.”
This disables exhaustiveness checking and you lose the main advantage of the sealed model: the compiler will no longer signal that you forgot to handle a new variant. As a result, the program will keep compiling but will start producing weird messages in unexpected places.
Mistake #2: storing errors in Ok (“Ok, but message = 'Error: ...'”).
This looks harmless, but it breaks the meaning of the model: you can no longer tell what happened from the result type. When reading code you’ll constantly doubt: “Is this success or just a string with scolding?” If it’s an error, it must be Error, not “success with a sad face.”
Mistake #3: returning null instead of Error.
The T? pattern is good for some tasks, but in command logic it’s too impoverished: null doesn’t explain the reason and is easy to lose. If an error is a normal outcome (for example, the user entered an invalid command), it’s better to return Error(reason) and handle it predictably.
Mistake #4: printing inside business functions while also returning a result.
Sometimes you see a hybrid: the function prints println("OK") and also returns Ok("..."). This leads to duplicate messages and confusion: where exactly is user output formed, who is responsible for it, why something printed twice. If you chose the CommandResult contract, it’s better to keep printing at the top level (in main or in a separate “UI” layer).
Mistake #5: making Ok too “thick” and Error too “thin.”
For example, Ok contains a message, and data, and some statistics, while Error is just the string "Error". In reality errors often require no less clarity: at least a clear reason. Even if for now we store only a reason string, it’s important that it be specific: “Amount must be > 0,” “Unknown command,” “Index out of range,” not just “Error.”
Mistake #6: turning a sealed result into “just another enum” by adding a bunch of nullable fields.
If you start writing something like data class Ok(val message: String, val removed: Expense?, val index: Int?), then you gradually slide back into a “universal bag of nullables.” It’s better to keep variants simple and meaningful: either different result variants, or separate functions for different scenarios. Today’s goal is contract clarity, not maximum “universality at any cost.”
GO TO FULL VERSION