CodeGym /Courses /Kotlin SELF /when as an expression

when as an expression

Kotlin SELF
Level 13, Lesson 2
Available

1. Why use when as an expression

When we write console programs, it’s very easy to slide into the style of “println(...) in every branch.” It works... while the program is small. But as soon as you want to compute the message text first and then decide where to send it (to the console, to a log, to a file), or you want to return a result from a function, you suddenly need a when that returns a value rather than just performing an action.

In Kotlin, when can be both a statement (statement) and an expression (expression). The difference is that an expression produces a result that you can assign to a variable or return from a function. Kotlin explicitly emphasizes this idea: when as an expression returns a value, while as a statement it simply executes code with no result.

Quick comparison: statement vs expression

What we want How we write it What we get
“Perform an action”
when (x) { ... -> println(...) }
We return nothing, we just execute
“Return a value”
val text = when (x) { ... -> "..." }
We get a value and use it later

This idea is described one-to-one in the official explanation of when as an expression vs a statement.

2. Basic syntax: val result = when (...) { ... }

Now we’ll take the most important step of the day: stop printing inside when (although sometimes you can), and start producing a string/number as a result. This is similar to if as an expression, which you’ve seen before: instead of “branching does something,” we switch to “branching chooses a value.”

The key form looks like this:

val message = when (x) {
    1 -> "..."
    2 -> "..."
    else -> "..."
}

Here message is a regular variable, and when (...) {...} is an expression that “evaluates” to a single value.

Example 1: choose a message by response code

fun main() {
    val code = 404

    val message = when (code) {
        200 -> "OK"
        404 -> "Not Found"
        else -> "Other code: $code"
    }

    println(message) // Not Found
}

Notice: we don’t print in the branches. We return strings, and we print once—after the when. This immediately creates order: “first decide what to say, then say it.”

3. Exhaustiveness and else

Now for the main “freeze-frame” of this lecture. When when is used as a statement (statement), Kotlin allows you not to cover all options: if no branch matches, nothing will happen. The official example shows exactly this behavior: not all cases are covered, no branch is selected, but there’s no error.

But when when is used as an expression, Kotlin requires exhaustiveness: an expression must have a result for any input. Otherwise, what should be assigned to the variable? “Nothing”? The compiler doesn’t agree.

Kotlin states it directly: if when is used as an expression, you must cover all cases, otherwise you’ll get a compilation error.

How the error looks in real life

Imagine you wrote this:

fun main() {
    val code = 500

    val message = when (code) {
        200 -> "OK"
        404 -> "Not Found"
        // no else
    }

    println(message)
}

The logic is clear: “for now I only care about 200 and 404.” But the compiler will say something like: “and what should I do if code equals 500?”—and it will be right. That’s why, in expression-style when, you’ll most often see else.

“else is not required”—but don’t rush to celebrate

In theory, you can omit else if you have guaranteed that you listed all possible options. Kotlin has types where this is realistic (for example, for certain closed sets of values), but then you’ll run into types that we will cover in detail later in the course.

At the current level, it’s easier to remember an honest beginner rule: if a when returns a value, you always need else.

4. The value of a branch: -> and a { ... } block

When a when branch is a single line after ->, everything is simple: that line is the value. But pretty soon you’ll want to do a couple of actions inside a branch: for example, prepare some text, normalize data a bit, or compute something step by step. Then the branch becomes a { ... } block.

And here it’s important to know the rule: the value of a block-branch is the last expression inside the block. Kotlin emphasizes that a branch may be a block, and its value will be the value of the last expression in that block.

Example 2: a block-branch returns the last expression

fun main() {
    val code = 400

    val message = when (code) {
        200 -> "OK"
        400 -> {
            val base = "Bad Request"
            "$base (check the input data)"
        }
        else -> "Other code: $code"
    }

    println(message) // Bad Request (check the input data)
}

Here we prepared the base variable inside the branch, and then returned a template string as the last line.

A nuance that saves hours of your life

If the last line in a branch is println(...), then the branch returns Unit, and the “fun” begins: different branches return different types. So, when you use when as an expression, try to keep branches “returning,” and do the printing outside.

5. The result type of when: all branches must agree

When when is an expression, it has one result, so it has one type. Kotlin will try to infer a common type for all branches. If one branch returns a String, another returns a Int, and a third returns Unit, then the common type becomes too “wide” (for example, Any), and it will be inconvenient to use downstream.

Instead of a technical phrasing, let’s remember the practical one: decide in advance what your when returns. If it’s a message, let all branches return a String. If it’s a number, let them return a number.

Example 3: when returns a number

fun main() {
    val month = 2

    val daysInMonth = when (month) {
        1, 3, 5, 7, 8, 10, 12 -> 31
        4, 6, 9, 11 -> 30
        2 -> 28
        else -> 0
    }

    println(daysInMonth) // 28
}

Yes, here we used grouping values with commas—this is legal and readable, and Kotlin presents this style as a standard technique for when.

And else -> 0 here is not “for looks”: it covers the case “the user entered 13.” We’re not validating ranges nicely yet—that will be the next lecture—but we already need exhaustiveness now.

6. Practice: when in functions, with null, and without else

In real programs, branching often lives inside functions: “take a code—return text,” “take a command—return a hint.” Kotlin even recommends in its style conventions using the expression form of if/when/try where you return a value, because it makes code shorter and more straightforward.

Next are a few typical situations where when as an expression is especially good.

when + functions: return a value without an if “spaghetti mess”

Let’s make a small function for our future console application (in the next lectures of the day we’ll start handling commands). For now, without input—just to see the architecture: the function returns a string.

fun statusText(code: Int): String = when (code) {
    200 -> "OK"
    400 -> "Bad Request"
    404 -> "Not Found"
    else -> "Unknown: $code"
}

fun main() {
    println(statusText(404)) // Not Found
}

It reads almost like a dictionary: “200—OK, 400—Bad Request...”. And most importantly: the function always returns a string, because the when is exhaustive.

Nullable values in when: a separate null branch

Now for a very real-life story: the user typed something, you tried to parse it, got an Int? (that is, “a number or null”), and then you need to respond nicely.

when is especially convenient here because you can handle null with a separate branch. This naturally fits with our previous experience with toIntOrNull() and basic null-safety.

fun main() {
    print("Enter your age: ")
    val raw = readln().trim()

    val age: Int? = raw.toIntOrNull()

    val message = when (age) {
        null -> "This doesn't look like a number: \"$raw\""
        0 -> "Age 0—sounds like the start of a programmer's career."
        else -> "Your age: $age"
    }

    println(message)
}

What matters here is that message is a string in any scenario. Even if age == null, we still return a string, which means the when is exhaustive.

Mini-refactor of a “console helper”: build the response first, then print

Now we’ll start building a style that will be especially useful in the lecture about commands. Imagine we have a “console helper”—an app that reacts to a command and outputs text. For now, without readln() and normalization (that will be in the next lecture of the level), just a sketch.

The key idea of this lecture: branching returns a string, and printing happens once.

fun replyFor(command: String): String = when (command) {
    "help" -> "Available commands: help, exit"
    "exit" -> "Shutting down..."
    else -> "Unknown command: $command"
}

fun main() {
    val cmd = "help"

    val reply = replyFor(cmd)
    println(reply) // Available commands: help, exit
}

See how convenient this is: replyFor(...) can be reused later. In the next lecture you’ll learn how to “pull” command out of user input, normalize it with trim().lowercase(), and then when will become a real command dispatcher. But the foundation is right here: when as an expression returns a result.

when without else: an example with Boolean

It’s useful to see a case where else really isn’t needed, to understand the idea of exhaustiveness rather than just memorizing “write else.”

A Boolean has only two values, and if you handle true and false, then you have handled everything. In this case, when is exhaustive without else.

fun main() {
    val isAdmin = true

    val access = when (isAdmin) {
        true -> "Access: full"
        false -> "Access: limited"
    }

    println(access) // Access: full
}

Why do I still not advise you to fanatically avoid else? Because as soon as nullable logic appears (Boolean?) or you make a more complex type, “everything is covered” will suddenly stop being obvious. At your current stage, else is not an enemy but insurance against compiler and user surprises.

7. Common mistakes when using when as an expression

Mistake #1: forgetting else and wondering why “the compiler suddenly complains.”
This is the most common situation: you wrote nice branching, assigned it to a val, and expect the program to just “do nothing” if nothing matches. But an expression must return a value, so else (or the full set of options) is mandatory. This is not Kotlin being picky; it’s logic: otherwise it’s unclear what to assign.

Mistake #2: returning different types from different branches and getting a weird common type.
For example, returning "OK" in one branch, 0 in another, and calling println(...) in a third. Kotlin will start looking for a common type, and you’ll end up with a result that’s inconvenient to work with. A good style is to choose the when “contract” in advance: return a string or return a number, and stick to that in all branches.

Mistake #3: printing (println) inside branches and then trying to use the result.
This is the trap of “I’m used to if/else where I performed an action.” If there is a println(...) inside a branch, that’s an action, not a value. As a result, you either won’t be able to assign the result, or you’ll get Unit. A practical technique: first compute val message = when (...) { ... }, and then do a single println(message) outside.

Mistake #4: using block-branches but forgetting that the last expression is returned.
Sometimes a person writes a block inside a branch, creates variables, and then accidentally leaves something “wrong” as the last line (for example, a function call that returns Unit). As a result, the branch returns Unit, and the when result type breaks. If a branch is a block, ask yourself: “what is the last line, and what does it return?” Kotlin explicitly describes the rule “the last expression is the branch value.”

Mistake #5: mixing everything in when at once: computation, input, printing, and error handling.
Even if it works, such code is hard to read: when turns into a small “program inside a program.” Keep branches short: let when answer the question “which result should I choose?”, and let the other actions (input/printing) live nearby and be clearly separate. This style is one of the reasons why Kotlin’s coding conventions prefer the expression form of conditional constructs: it makes the logic direct.

1
Task
Kotlin SELF, level 13, lesson 2
Locked
Report quarters
Report quarters
1
Task
Kotlin SELF, level 13, lesson 2
Locked
Pass to the admin panel
Pass to the admin panel
1
Task
Kotlin SELF, level 13, lesson 2
Locked
Payment status
Payment status
1
Task
Kotlin SELF, level 13, lesson 2
Locked
Receipt discount
Receipt discount
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION