CodeGym /Courses /Kotlin SELF /if as an expression in Kotlin: assigning the branching re...

if as an expression in Kotlin: assigning the branching result

Kotlin SELF
Level 3, Lesson 5
Available

1. Introduction

If you’ve just learned if, your brain may still see it as a “crossroad”: if the condition is true, go left and do something; otherwise, go right and also do something. And that’s fine. But in real programs, we often need not only to “do an action”, but to get the result of a choice: a string, a number, a label that we’ll use later.

Imagine choosing which sign to hang on a door: "Open" or "Closed". It’s not an action for the sake of action—it’s a value that you need to store and then print. Kotlin says here: “OK, let if return the sign right away.” And it’s very convenient.

if as a statement and if as an expression

When we write if “the old way”, it works as a statement: it executes or doesn’t execute a chunk of code, and that’s it.

But Kotlin allows using if as an expression, meaning as something that has a value, like 3 + 4 or "Hi".length. This is an official language feature: if can be written as an expression and its result can be assigned to a variable, but then the else branch becomes mandatory.

To grasp the idea, let’s compare two styles: “first create a box (var), then put the result into it” versus “get the result right away”.

Here’s the style you already know (statement-style if):

fun main() {
    val temperature = 28

    var label = "Normal"
    if (temperature > 25) {
        label = "Hot"
    }

    println(label) // Hot
}

Here if doesn’t “return” anything. We simply change label.

And here’s the style we want to learn today (if as an expression):

fun main() {
    val temperature = 28

    val label = if (temperature > 25) "Hot" else "Normal"
    println(label) // Hot
}

The semantic difference is this: in the second variant, we tell Kotlin directly: “label is the result of a choice”.

Basic syntax: val x = if (cond) A else B

The basic form is: val result = if (condition) value1 else value2. It reads almost like a human sentence: “result equals (if condition then value1 else value2)”.


val result = if (condition) value1 else value2
Basic syntax: if as an expression

A classic example that always lands well is the absolute value of a number. In math it’s |x|, and in code we simply choose: either x, or -x.

fun main() {
    val x = -7

    val abs = if (x >= 0) x else -x
    println("abs = $abs") // abs = 7
}

Notice: we don’t use var at all here. It’s a small but important win: fewer mutable variables means fewer places where you can “accidentally break everything”.

Why else is mandatory

From a beginner’s perspective, the requirement “why can’t I write val r = if (cond) 1?” can feel nitpicky. But the compiler isn’t being mean—it’s enforcing logic: if you assign a result, then the result must exist always, for any outcome of the condition.

Kotlin states explicitly: if if is used as an expression, the else branch is required.

Bad example (not allowed):

fun main() {
    val isVip = true
    val discount = if (isVip) 10 // Compilation error: no else
}

Good example (correct):

fun main() {
    val isVip = true

    val discount = if (isVip) 10 else 0
    println("discount = $discount") // discount = 10
}

A handy rule to remember here: if if appears on the right side of = and you want to store the result, then else is always required.

Block branches { ... }: the value is the last expression

Often you need to do more than one thing inside a branch: for example, print an explanation and only then return a value. Kotlin allows each branch to be a block { ... }. In that case, the branch result is the last expression in the block.

Let’s make a mini-example: choose who to consider “taller”—Alice or Bob—while also printing who we chose (as if writing a log).

fun main() {
    val heightAlice = 160
    val heightBob = 175

    val taller = if (heightAlice > heightBob) {
        println("Chose Alice") // Chose Alice (if the condition were true)
        heightAlice
    } else {
        println("Chose Bob")  // Chose Bob
        heightBob
    }

    println("taller = $taller") // taller = 175
}

Notice the “trick”: println(...) is not the value assigned to taller. The value is the last line of the branch (heightAlice or heightBob). This is a very important habit: at the end of the branch of an if expression you should place what you want to return.

A small diagram of how it works

flowchart TD
    A["if (condition)"] -->|true| B["then branch { ... }"]
    A -->|false| C["else branch { ... }"]
    B --> D["value = last expression of then branch"]
    C --> E["value = last expression of else branch"]
    D --> F["result of the if expression"]
    E --> F

2. else if and a linear coding style

Sometimes we don’t have “two options” but “three or four”. The good news is that an if / else if / else chain can also be an expression. That is, we can assign the result immediately, without intermediate vars.

Example: we have a number x, and we want to get a string "positive", "negative", or "zero".

fun main() {
    val x = 0

    val sign = if (x > 0) {
        "positive"
    } else if (x < 0) {
        "negative"
    } else {
        "zero"
    }

    println(sign) // zero
}

This style is especially nice because the variable sign immediately has a clear meaning: “this is the sign label of the number”.

How an if expression helps keep code “linear”

Before if expressions, people often write: “declare a var, then assign in different branches”. It works, but over time it leads to a variable that lives too long and changes too many times.

Let’s compare two approaches on a realistic task: if a string is empty, replace it with "EMPTY", otherwise keep it as is (after trim()).

Approach with var:

fun main() {
    val raw = "   Kotlin   "
    val trimmed = raw.trim()

    var label = "EMPTY"
    if (trimmed.length != 0) {
        label = trimmed
    }

    println(label) // Kotlin
}

Approach with an if expression:

fun main() {
    val raw = "   Kotlin   "
    val trimmed = raw.trim()

    val label = if (trimmed.length == 0) "EMPTY" else trimmed
    println(label) // Kotlin
}

The second version reads faster: “label is either "EMPTY" or trimmed”. And most importantly, label is now a val, which means you can’t accidentally change the “door sign” in the middle of the program.

3. Practical example: “Discount checkout”

Now we’ll build a small console program that looks like a real scenario: the user enters an order amount, and we calculate the discount and print the final total. This is an honest practice exercise where you can clearly see how if as an expression simplifies the code.

The idea:

1) read the amount (as a string), trim whitespace, try to parse it as a number via toIntOrNull();
2) if it’s not a number, print an error message;
3) if it is a number, determine the discount percentage: if the amount is >= 1000, then the discount is 10%, otherwise 0%;
4) build the message and print it.

Step 1. Choose the discount percentage as a value

Let’s start with the most important thing for this lecture—assigning the result of branching:

fun main() {
    val sum = 1200

    val discountPercent = if (sum >= 1000) 10 else 0
    println("discountPercent = $discountPercent") // discountPercent = 10
}

You can see the key point: discountPercent is the result of a choice, so an if expression is a perfect fit.

Step 2. The message can be “computed” too

Beginners often do this: in each if branch they print almost the same text. It works, but quickly leads to duplication. Instead, we can compute the message string and keep printing to a single line.

fun main() {
    val finalSum = 950
    val discountPercent = 0

    val message = if (discountPercent > 0) {
        "Discount $discountPercent% applied. Total: $finalSum"
    } else {
        "No discount. Total: $finalSum"
    }

    println(message) // No discount. Total: 950
}

Notice: we use blocks { ... }, but the last line is a string, not println.

Step 3. Full version of main

Below is a complete example. It’s a bit longer than the individual snippets (because a real program still does input/validation), but all techniques here are already familiar.

fun main() {
    print("Enter the order amount: ")
    val sumText = readln().trim()
    val sum = sumText.toIntOrNull()

    if (sum == null) {
        println("Error: you need to enter an integer.") // Error: you need to enter an integer.
    } else {
        val discountPercent = if (sum >= 1000) 10 else 0
        val discount = sum * discountPercent / 100
        val finalSum = sum - discount

        val message = if (discountPercent > 0) {
            "Discount $discountPercent% (-$discount). Total: $finalSum"
        } else {
            "No discount. Total: $finalSum"
        }

        println(message) // example: Discount 10% (-120). Total: 1080
    }
}

There’s an important mindset here: we try to make variables “one-time facts”. discountPercent, discount, finalSum, message are not “boxes that change”, but “results of computations”. Once you get used to this, the code becomes more predictable: you read it top to bottom, like a recipe.

1
Task
Kotlin SELF, level 3, lesson 5
Locked
Debt absolute value
Debt absolute value
1
Task
Kotlin SELF, level 3, lesson 5
Locked
Door sign
Door sign
1
Task
Kotlin SELF, level 3, lesson 5
Locked
Player rating
Player rating
1
Task
Kotlin SELF, level 3, lesson 5
Locked
Username without surrounding spaces
Username without surrounding spaces
1
Survey/quiz
Conditional statements and logic, level 3, lesson 5
Unavailable
Conditional statements and logic
Conditional statements and logic
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION