CodeGym /행동 /Kotlin SELF /Errors and style when

Errors and style when

Kotlin SELF
레벨 13, 레슨 5
사용 가능

1. When when becomes a problem

If you’re thinking right now: “But my when works—why talk about style?”, then you’re already on the right track. In programming, style is not about aesthetics for aesthetics’ sake—it’s about predictability. You write code once, but you read (and fix) it many times, sometimes in a state of “I didn’t sleep enough, the coffee is gone, and it’s crashing”.

when is good because the reader can see: “here are the options, here are the actions”. But when has three typical “pain points” that beginners run into almost always:

  1. branches start to overlap, and the logic depends on line order (a hidden trap);
  2. else is either forgotten, or used as a trash bin “just in case”;
  3. branches grow, and when stops being a table and turns into a mini-program inside the program.

To treat these issues, remember a basic rule: when checks branches top to bottom and triggers the first matching one. It’s not “best match search”, it’s “first match wins”.

2. Overlapping conditions: when line order becomes logic

When you write conditions in when, it’s easy to start thinking: “Well, I listed everything—so everything is covered.” And then an unpleasant surprise appears: if conditions overlap, some branches become unreachable or start firing not where you expect. Even worse, the code will compile and “seem to work”, but sometimes produce the wrong result.

Classic trap: a wide range “captures” a narrow one

First, let’s make a small example of “how not to do it”. It compiles and runs, but the logic deceives us.

fun main() {
    val score = 42

    val label = when (score) {
        in 0..100 -> "Normal range"
        in 0..50 -> "Rather low"
        else -> "Invalid"
    }

    println(label) // Normal range
}

If you expected “Rather low”, that’s normal: you’re thinking like a human (“42 fits both, but 0..50 feels more specific”). But when thinks like a machine: the first branch already matched—so we don’t even check the others.

The correct fix is not magical: we simply put the narrower condition first.

fun main() {
    val score = 42

    val label = when (score) {
        in 0..50 -> "Rather low"
        in 51..100 -> "Normal range"
        else -> "Invalid"
    }

    println(label) // Rather low
}

Here we made the ranges non-overlapping, and branch order stopped being hidden logic.

A “guard” branch with !in: useful, but requires discipline

Validation via !in looks nice: first filter out obviously invalid values, then classify the rest. This is a genuinely good pattern—you just need to understand that !in is usually a wide condition, and it must be placed where it won’t break other checks.

fun main() {
    val temperature = 999

    val message = when (temperature) {
        !in -50..60 -> "Out of a reasonable range"
        in -50..0 -> "Cold"
        in 1..25 -> "Normal"
        else -> "Hot"
    }

    println(message) // Out of a reasonable range
}

Everything is fine here: !in -50..60 does not overlap with the other branches, because the other branches are entirely inside the -50..60 range.

If you accidentally write the ranges so that the “reasonable” range and the “categories” don’t align, you’ll get strange behavior. So the practical rule is simple: either make branches non-overlapping, or (if they overlap) put narrower ones above and use the order consciously.

Mini-diagram: how branch order works

Sometimes it helps to literally draw what’s happening:

flowchart TD
    A[Value x] --> B{Does the first branch match?}
    B -- yes --> C[Execute the first branch]
    B -- no --> D{Does the second branch match?}
    D -- yes --> E[Execute the second branch]
    D -- no --> F{...}
    F -- no --> G["else (if present)"]

The diagram is trivial, but it explains 90% of “why did it behave like that?”

3. else, exhaustiveness, and “silent” when

else is not a “mandatory patch”, but a way to explicitly say: “I accounted for everything else”. The nuance is that requirements for else depend on whether you use when as an expression or as a statement. And this is where typical mistakes start: somewhere the compiler complains, and somewhere it stays silent—and the program “does nothing”.

Kotlin clearly distinguishes when as a statement vs an expression, and expression requires exhaustiveness: you must return a value for any input.

The “it did nothing” mistake (when when is a statement)

If when is used as a statement (i.e., we don’t assign its result to a variable), Kotlin allows you not to cover all cases. This can be convenient, but for a beginner it’s often a trap: “I thought it would at least say the command is unknown.”

fun main() {
    val cmd = "unknown"

    when (cmd) {
        "help" -> println("Help")
        "exit" -> println("Exit")
    }

    println("After when") // After when
}

The program “silently” skipped the when. No error. Sometimes that’s fine. But for a command-line interface it’s almost always a bad idea: the user enters a command and gets silence. Therefore, in command handling, else is not an option—it’s basic politeness.

fun main() {
    val cmd = "unknown"

    when (cmd) {
        "help" -> println("Help")
        "exit" -> println("Exit")
        else -> println("Unknown command: $cmd") // Unknown command: unknown
    }
}

The “doesn’t compile” mistake (when when is an expression)

When when returns a value, the compiler requires exhaustiveness—otherwise it can’t guarantee that the variable will receive a value. This is not “Kotlin being picky”; it’s real protection against holes in your logic.

fun main() {
    val cmd = "help"

    // Not allowed: no else, so not all cases are covered
    // val message = when (cmd) {
    //     "help" -> "Help"
    // }

    val message = when (cmd) {
        "help" -> "Help"
        else -> "Unknown command: $cmd"
    }

    println(message) // Help
}

else as diagnostics, not as “whatever”

A very common mistake is to do else -> "" or else -> 0 just to “make the compiler stop complaining”. Formally it works, but you’re disabling diagnostics for yourself. In commands, else should help you understand what went wrong: print the original value, say what was expected, and not hide the problem.

4. Long branches: how not to turn when into a mini-program

When you’re learning, it’s tempting to write everything in one branch: parse a number, validate a range, print three lines, update state. That’s fine as a first step, but once a branch becomes longer than 10–15 lines, when stops doing its main job—being a table of options.

Kotlin style (and common sense) usually recommends preferring the expression form of when, if, try where that makes code shorter and clearer. But “shorter” does not mean “one giant branch”.

Bad style: when does everything at once

Let’s imagine a command grade <number> that prints a grade based on points. Here’s an example that works, but is hard to read.

fun main() {
    val arg = "72"
    val points = arg.toIntOrNull()

    when (points) {
        null -> println("A number is required")
        else -> {
            if (points < 0 || points > 100) {
                println("Must be 0..100")
            } else if (points >= 90) {
                println("A")
            } else if (points >= 80) {
                println("B")
            } else {
                println("C or lower")
            }
        }
    }
}

Three levels got mixed: parsing, validation, and business logic. In a small example it’s tolerable, but in a real app the branch quickly inflates.

Better: when returns a result, and printing is separate

Let’s implement two ideas: first, when returns a string; second, inside when we avoid nested if when we can do it more neatly.

fun gradeMessage(points: Int?): String {
    return when (points) {
        null -> "A number is required"
        !in 0..100 -> "Must be 0..100"
        in 90..100 -> "Grade: A"
        in 80..89 -> "Grade: B"
        else -> "Grade: C or lower"
    }
}

fun main() {
    val points = "72".toIntOrNull()
    val message = gradeMessage(points)

    println(message) // Grade: C or lower
}

We gained in several places at once. when became a table. Branches are short. Printing happens once. The logic became testable even “in your head”: you can scan the branches and see the coverage.

Technical nuance: a branch with a block is fine, but keep the block small

Sometimes you really need to do two actions in a branch. That’s acceptable. Just keep the block compact, and if you’re already adding another when or three if statements inside, that’s a signal to extract the piece into a function.

fun main() {
    val cmd = "help"

    when (cmd) {
        "help" -> {
            println("Commands: help, grade <0..100>, exit") // Commands: help, grade <0..100>, exit
            println("Example: grade 90")                    // Example: grade 90
        }
        else -> println("Unknown command: $cmd")
    }
}

5. Choosing a form: if vs when (value) vs when { ... }

This part may feel like personal preference, but in practice it’s a real tool against mistakes. If you choose the branching form by meaning, the code becomes simpler, and overlapping conditions happen less often. Kotlin conventions explicitly recommend: for binary conditions, if is often better, and when is for three or more options.

if — when there are truly two options

If you have exactly two paths, if is usually more readable. Not because when is “bad”, but because if reads in your head like “either this, or that”.

fun main() {
    val raw = "   "

    val input: String? = if (raw.trim().isEmpty()) null else raw.trim()
    println(input) // null
}

You can also do it with when, but it will look like a “two-row table”, which is usually unnecessary.

when (value) — when comparing against specific values

Commands, codes, statuses are the native territory of when (value): it reads like a mapping table.

fun main() {
    val role = "editor"

    val access = when (role) {
        "viewer" -> "Read-only"
        "editor" -> "Can edit"
        "admin" -> "Can do everything (and even accidentally delete the world)"
        else -> "Unknown role: $role"
    }

    println(access) // Can edit
}

when { ... } — when branches are conditions, not values

The when { ... } form is a great replacement for a chain of if/else if when you classify by conditions. In this form, else is mandatory: without it, the compiler won’t let you build the code, because otherwise it’s unclear what to do if no condition is true.

fun main() {
    val x = 0

    val sign = when {
        x < 0 -> "negative"
        x == 0 -> "zero"
        else -> "positive"
    }

    println(sign) // zero
}

Pitfall: when { ... } is easier to “break” with overlaps

When conditions are boolean, overlaps are even easier to create accidentally. For example, if you first write x >= 0, and then x == 0, the branch x == 0 will never run.

fun main() {
    val x = 0

    val label = when {
        x >= 0 -> "Non-negative"
        x == 0 -> "Zero"
        else -> "Negative"
    }

    println(label) // Non-negative
}

The fix is simple again: put the narrower one above, or make the conditions mutually exclusive.

6. Style for command when: a neat command table

Now we’ll assemble everything into that “command dispatcher” you started building in the previous lecture. Our goal is not to add new features, but to show style: normalize before when, keep branches short, handle unknown cases explicitly, and don’t hide overlaps inside line order.

Step 1: normalize and split input into command and arg

Let’s make a small function that takes an already trimmed string and returns a pair: command and argument. We use only familiar tools: indexOf and substring.

fun splitCommand(line: String): Pair<String, String> {
    val spaceIndex = line.indexOf(' ')
    val command = if (spaceIndex == -1) line else line.substring(0, spaceIndex)
    val arg = if (spaceIndex == -1) "" else line.substring(spaceIndex + 1).trim()
    return command.lowercase() to arg
}

What matters here: splitCommand doesn’t read input and doesn’t print. It only transforms a string. Such a piece is easy to reuse and hard to “break by accident”.

Step 2: when as an expression that returns a response

Now let’s make a handler that returns a response string. This reduces the temptation to print in every branch, and it also helps avoid “sheet” branches: a branch should boil down to computing a response.

fun handleCommand(command: String, arg: String): String {
    return when (command) {
        "help", "h", "?" -> "Commands: help, grade <0..100>, echo <text>, exit"
        "echo" -> arg
        "grade" -> gradeMessage(arg.toIntOrNull())
        "exit" -> "EXIT"
        else -> "Unknown command: $command"
    }
}

Notice the style: we grouped command synonyms with commas to avoid duplicating the same action. This syntax is one of the reasons why when is often more readable than a chain of if/else if.

Step 3: main becomes a simple “pipeline”

All that’s left is to assemble a small loop. We already know while, so everything is straightforward.

fun main() {
    while (true) {
        print("> ")
        val raw = readln().trim()

        if (raw.isEmpty()) {
            println("Enter a command. For help: help") // Enter a command. For help: help
            continue
        }

        val (command, arg) = splitCommand(raw)
        val response = handleCommand(command, arg)

        if (response == "EXIT") break
        println(response)
    }
}

This is a good example of why we talk about when style at all. You get a “layer cake” (in a good sense): input → preparation → parsing → dispatching → output. And each place does one job.

A small diagram of the command pipeline

Sometimes it’s useful to see it as an assembly line:

flowchart LR
    A["readln()"] --> B["trim()"]
    B --> C{isEmpty?}
    C -- yes --> D[message + continue]
    C -- no --> E[splitCommand]
    E --> F[handleCommand with when]
    F --> G[println/exit]

And yes: if you felt like an engineer at a factory—congratulations, you just took your first step toward architecture.

When when starts to grow

In real life, there are more commands. Branches grow. And one day your beautiful when (command) turns into an 80-line canvas, where half the branches also repeat the same thing. That’s not “bad”, it’s natural growth. The important thing is to notice in time when when stopped being a table.

Typical signs: nested if appears inside branches, repeated parsing like arg.toIntOrNull(), identical error messages, and you start scrolling when with the mouse wheel.

The simplest way to contain growth is not to try to “defeat” when, but to help it: extract repeated pieces into functions and prepare data before dispatching. For example, if half the commands work with a number, you can make one argument-parsing function that returns Int?, and then use its result in when. This is not a new topic—it’s ordinary decomposition with functions that you’ve already practiced.

7. Typical mistakes when working with when style

Mistake #1: overlapping conditions where branch order becomes hidden logic.
The most insidious situation is when the code compiles and “often works”, but a lower branch never triggers because a broader range or condition sits above it. This is fixed either by reordering branches (narrow above broad) or by making conditions mutually exclusive so you stop depending on order.

Mistake #2: else is used as a “trash bin” to make the compiler stop complaining.
When when is an expression, the compiler requires exhaustiveness. Beginners sometimes write else -> "" or else -> 0. Formally the program builds, but you lose diagnostics: an error turns into a silent wrong result. It’s better to make else meaningful: report the unknown value, show the original input.

Mistake #3: when without else in commands becomes “silence” for the user.
When when is used as a statement, Kotlin allows you not to cover all cases, and if nothing matches—nothing happens. For a command interface this is almost always bad UX: a person entered a command and didn’t understand what happened. Therefore, in command handling, else is a mandatory “unknown command” branch.

Mistake #4: branches become too long, and when stops being a table.
As soon as parsing, validation, multiple println, nested if, and another when appear inside a branch, readability drops sharply. The right habit is to return a result (string/status) from when, and move details into functions. This makes code linear and helps keep branches short.

Mistake #5: using when where if is simpler, and vice versa.
If there are exactly two options, if usually reads faster. Kotlin conventions explicitly advise preferring if for binary conditions and when for three or more options. The reverse mistake is writing a long chain of if/else if where the meaning is a “value table”: there, when (value) makes code more uniform and reduces duplication.

Mistake #6: normalizing input inside branches instead of before when.
If in every branch you write raw.trim().lowercase() or do substring() directly in when conditions, your when stops being a dispatcher: it becomes “the place where we do everything at once”. It’s much more reliable to compute command and arg once, and have when work with already clean values.

1
과제
Kotlin SELF, 레벨 13, 레슨 5
잠금
점수에 따른 등급
점수에 따른 등급
1
과제
Kotlin SELF, 레벨 13, 레슨 5
잠금
정중한 봇
정중한 봇
1
과제
Kotlin SELF, 레벨 13, 레슨 5
잠금
배송 요금
배송 요금
1
과제
Kotlin SELF, 레벨 13, 레슨 5
잠금
주문 상태
주문 상태
1
설문조사/퀴즈
<code><span class="text-user">when</span></code> opeoreiteo, 레벨 13, 레슨 5
사용 불가능
when opeoreiteo
when: bun-gi, yuhyo seong geomjeung, keomaendeu
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION