CodeGym /행동 /Kotlin SELF /when ( value ) as a replacement for if/ else if

when ( value ) as a replacement for if/ else if

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

1. Why you need when instead of long if/else if

Almost any program that communicates with a person (or with another program) sooner or later starts choosing behavior by a “code”: by number, by string, by character. At first everything looks fine: two options — two ifs. But as soon as there are 4–6 options, the else if chain starts stretching downward like a supermarket receipt where you bought “something on sale” and suddenly realized it was a ladle for 69 euros.

The problem is not that if/else if is bad. It is great. The problem is that a long chain is harder to read: it is harder for the eye to see “here is the list of all options”, and harder to understand what happens if the value does not match any option. Kotlin gives us a more “table-like” form of such branching — when.

Let us start with a very typical situation: there is a value, and we want to perform different actions for different values.

fun main() {
    val role = "editor"

    if (role == "viewer") {
        println("Access: read-only")
    } else if (role == "editor") {
        println("Access: editing")
    } else {
        println("Unknown role: $role")
    }
}

The code works. But if the number of roles becomes 6, it will start to look less friendly. That is where when comes in.

The idea of when: a “mapping table” instead of a “ladder of conditions”

It is convenient to read when (value) like this: “I have a value value; if it equals this — do this; if it equals another — do that; otherwise — do the fallback option”. In meaning it is very similar to switch from other languages, but in Kotlin the syntax is usually cleaner and more predictable.

So instead of a if/else if/else “ladder” we get a construct that visually looks like a list of options. This is especially nice when you write menus, process error codes, modes of operation, commands, and other behavior switches.

Let us rewrite the role example using when:

fun main() {
    val role = "editor"

    when (role) {
        "viewer" -> println("Access: read-only")
        "editor" -> println("Access: editing")
        else -> println("Unknown role: $role")
    }
}

Here you can immediately see “which options are supported” and “what happens otherwise”.

2. when (value) syntax and reading rules

Basic syntax: when (value) { ... }

The syntax of when looks like this: first we write when (value), then curly braces, and inside — branches. Each branch in the basic form looks like “value -> action”.

It is important to get used to three elements:

  1. value — what we compare (for example, a menu number or a mode string).
  2. To the left of -> — “what we compare against”.
  3. To the right of -> — what to execute if it matches.

Mini-template (almost like a cheat sheet, but legal):

fun main() {
    val x = 2

    when (x) {
        1 -> println("One")     // One
        2 -> println("Two")      // Two
        else -> println("Other")
    }
}

It looks simple, but behind this simplicity there is important logic: checks go from top to bottom, and the first matching branch is executed.

else — the “just in case” branch that makes a program more robust

When a person enters data, sometimes they enter the wrong thing. Sometimes intentionally. Sometimes accidentally. Sometimes a cat walks across the keyboard — and that is also user input, just in “cat mode”. So the else branch in when is insurance: “all other values that I did not list”.

There is an important nuance: if when is used as a statement (i.e., it just performs actions), Kotlin does not require you to handle all cases. Then, if the value does not match any branch, nothing will be executed.

However, in learning and practical console programs it is almost always better to explicitly write else so the user gets a clear response.

Example of “polite” handling of an unknown value:

fun main() {
    val day = 9

    when (day) {
        1 -> println("Mon")                        // will not run
        2 -> println("Tue")                        // will not run
        3 -> println("Wed")                        // will not run
        else -> println("Unknown day: $day") // Unknown day: 9
    }
}

It almost always makes more sense to put else at the end — then the “options table” reads top to bottom, and “otherwise” really means “otherwise”.

Branch as a block: when one branch needs multiple actions

It often seems that a when branch must be “one action on one line”. In fact, a branch can do multiple actions: just put a block { ... } to the right of -> instead of a single expression.

This is especially useful when you want, for example, to print two messages, or first compute something and then print the result. While we use when as a statement (i.e., “we perform actions”), this looks very natural.

Example with a “multi-line response”:

fun main() {
    val code = 400

    when (code) {
        200 -> println("OK") // will not run
        400 -> {
            println("Bad Request")      // Bad Request
            println("Check the request") // Check the request
        }
        else -> println("Other code: $code")
    }
}

Note: the curly braces inside a branch are not “braces of when”, but specifically “branch braces”, i.e., a mini body where you can write multiple lines.

How a branch is chosen: top-to-bottom order and “first match wins”

It is very important to understand the branch selection mechanics; otherwise you can accidentally write code that looks logical but works “not like you expect”. when compares the value against the branches in order, from top to bottom, and as soon as it finds a match — it executes that branch and exits.

In this lecture we will not do branches with ranges and conditions (that is a separate topic), but even in a simple “equality” comparison it is useful to keep this in mind: the order of branches is part of the logic.

The execution scheme looks roughly like this:

flowchart TD
    A["There is a value x"] --> B["Compare with the first branch"]
    B -->|match| C["Execute actions of branch 1 and exit"]
    B -->|no match| D["Compare with the second branch"]
    D -->|match| E["Execute actions of branch 2 and exit"]
    D -->|no match| F["..."]
    F --> G["If nothing matched → else (if present)"]

From this follows a simple style rule: keep else at the bottom, and list options top to bottom in the order you want people to read them.

3. Practice: “Wallet” menu and switching to when

Now we will do a practical piece that clearly shows the benefit of when: handling the choice of a menu item. We will write a small “wallet” — an application that stores the current balance (just a number) and offers the user to choose an action. We will not use collections or complex data structures: our goal is to learn how to switch behavior by a value, not to build a bank.

Print the menu and read the choice

fun main() {
    println("=== Wallet ===")
    println("1 — show balance")
    println("0 — exit")

    print("Your choice: ")
    val choice = readln().trim()
    println("You chose: $choice") // for example: You chose: 1
}

For now, the choice is a string. That is fine: readln() always reads a string, and we prepare it via trim() (remove extra spaces).

Convert input to a number safely

We already know how to do it: toIntOrNull() returns Int?, i.e., either a number or null if the user entered something that is not a number.

fun main() {
    print("Your choice: ")
    val choice = readln().trim().toIntOrNull()

    if (choice == null) {
        println("You must enter a number.") // You must enter a number.
        return
    }

    println("You entered the number: $choice")
}

Here we use an “early exit” (return) so that we only work with valid data further on.

The same logic using if/else if, so we have something to compare to

Let us assume we have a balance.

fun main() {
    var balance = 100

    print("Your choice (1/0): ")
    val choice = readln().trim().toIntOrNull() ?: return

    if (choice == 1) {
        println("Balance: $balance") // Balance: 100
    } else if (choice == 0) {
        println("Exit") // Exit
    } else {
        println("Unknown command: $choice")
    }
}

It works, but you can already see that it is a “staircase”.

Rewrite using when (choice)

Now we do the same thing using when. Essentially we turn branching into a “table”: “1 → show balance”, “0 → exit”, “otherwise → error”.

fun main() {
    var balance = 100

    print("Your choice (1/0): ")
    val choice = readln().trim().toIntOrNull() ?: return

    when (choice) {
        1 -> println("Balance: $balance") // Balance: 100
        0 -> println("Exit")            // Exit
        else -> println("Unknown command: $choice")
    }
}

In terms of behavior, the program did not become “smarter”. But in terms of reading code, it became calmer: less visual noise, more of a “list of options” feel.

Add more actions to feel the scalability

Let us add “top up” and “spend” items. We will make the operations as simple as possible: read a number and change the balance. Here when starts to look especially appropriate.

fun main() {
    var balance = 100

    println("1 — balance, 2 — top up, 3 — spend, 0 — exit")
    print("Your choice: ")
    val choice = readln().trim().toIntOrNull() ?: return

    when (choice) {
        1 -> println("Balance: $balance") // Balance: 100
        2 -> { print("Amount: "); balance += readln().trim().toInt() }
        3 -> { print("Amount: "); balance -= readln().trim().toInt() }
        0 -> println("Exit")
        else -> println("Unknown command: $choice")
    }
}

Notice that we made branches 2 and 3 blocks { ... }, because there are two actions: ask for the amount and change the balance. This “block in a branch” technique is a normal part of when.

Yes, you can improve safety here (for example, guard against non-numeric amounts), but we will do that gradually: today our goal is to learn to choose behavior by value in a clean and readable way.

Make the menu “real”: loop + when

A menu is usually not one-time: the user chooses an action multiple times. We have while, so let us assemble a simple version of “keeps running until we exit”. Inside there will be when, which routes actions.

fun main() {
    var balance = 100
    var running = true

    while (running) {
        print("1-balance 2+ 3- 0-exit: ")
        val choice = readln().trim().toIntOrNull() ?: continue

        when (choice) {
            1 -> println("Balance: $balance")
            2 -> { print("Amount: "); balance += readln().trim().toInt() }
            3 -> { print("Amount: "); balance -= readln().trim().toInt() }
            0 -> { println("Bye!"); running = false } // Bye!
            else -> println("Unknown: $choice")
        }
    }
}

Notice the neat combination: if choice cannot be parsed, we do continue and simply retry input. This is not a when topic, but it is a typical “skeleton” of console programs: loop + read + branching.

4. Typical mistakes when working with when (value)

At the beginning, when often seems “too simple to make mistakes”, but mistakes still happen — mostly due to readability and habits after if/else. The good news: these mistakes are rarely complex, and you can almost always spot them by eye if you learn to read when as a table of options rather than as “yet another if”.

Mistake 1: forgetting about else and getting “silent behavior”.
Technically, when as a statement does not have to be exhaustive: if no branch matches, nothing will be executed. But in learning tasks and CLI programs this is usually bad UX: the user enters “9”, and the program looks like it froze (although it just did nothing). Most often it is better to explicitly write else and print a clear message.

Mistake 2: placing else not last and hiding the meaning of branches below.
The logic of when is top to bottom: the first matching branch “wins”. If you put else earlier, everything below becomes unreachable or pointless. Even when the compiler does not complain, the code reader gets nervous: “why are there branches if there is an else above?”. Keep else at the end as a style rule.

Mistake 3: inflating branches to 20–30 lines and turning when into a “mini program”.
when is good as a dispatcher: choose an option and run the right action. When half of the application appears inside a branch, the “options table” stops being a table and becomes a long sheet. In such cases, discipline helps: keep the branch short, and move details into a separate function (you already know how to write them).

Mistake 4: trying to replace if where there are only two options.
By Kotlin conventions, if is usually preferred for a binary choice, and when is used when there are three or more options. This is not a “law”, but a good guideline: if you have “yes/no”, if is often easier to read than when for a single check and an else.

Mistake 5: comparing “dirty input” as-is and being surprised that branches do not trigger.
Today we mostly compared numbers, but even there there is “dirt” (spaces, empty string, non-numeric characters). If a value comes as a string, without normalization (trim(), sometimes lowercase()) you can get a situation where “the user entered it correctly, but the program thinks otherwise”. The habit “prepare the input first, then branch” saves hours of debugging and helps preserve a little faith in humanity.

1
과제
Kotlin SELF, 레벨 13, 레슨 1
잠금
주간 내비게이터
주간 내비게이터
1
과제
Kotlin SELF, 레벨 13, 레슨 1
잠금
시스템의 역할
시스템의 역할
1
과제
Kotlin SELF, 레벨 13, 레슨 1
잠금
포켓 계산기
포켓 계산기
1
과제
Kotlin SELF, 레벨 13, 레슨 1
잠금
응답 모니터링
응답 모니터링
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION