Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 134 ยท Control Flow

if as an Expression

Learn Kotlin's if expression - if/else as a value, blocks that return their last line, else-if chains, why Kotlin has no ternary operator, the missing else error, and smart casts in conditions.

In many languages if is a statement: it does something (runs one block or another) but has no value. Kotlin's if is an expression: it produces a value you can store, return or pass along. That small difference removes the need for the ternary operator condition ? a : b, makes many functions shorter, and nudges you toward val instead of var.

This lesson starts with the familiar statement form, then shows the expression form, blocks as values, the rule about else, and the pitfalls professionals watch for. For the multi-way cousin, continue with when Expressions.

if as a statement

You can use if exactly as you would in Java or Python, to run code only when a condition is true. The condition must be a Boolean: Kotlin has no "truthy" or "falsy" values, so if (1) or if (name) is a compile error.

Kotlin if, else if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Conditions are checked from top to bottom and the first true branch runs; the others are skipped. Put the most specific test first, or a broad one will shadow the rest.

if as an expression

Because if produces a value, you can assign it directly:

Kotlin Assigning the result of if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The type of the whole expression is the common type of its branches. Here both branches are String, so category is a String. Notice what you did not need: a mutable var category that you assign in each branch. The expression form gives you an immutable val whose value is fixed in one place, and that is easier to reason about.

No ternary operator

Kotlin deliberately omits condition ? a : b. The ? and : symbols are used for nullable types and the Elvis operator, and if (condition) a else b already does the job in about the same space. For three-way choices, chain else if, or use when, which reads better than nested ternaries ever did.

Blocks as values

A branch may be a block in braces. A block used as an expression evaluates to its last expression. There is no return keyword involved:

Kotlin The last expression of a block is its value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Variables declared inside a branch, like rate above, exist only within that block. This keeps temporary names out of the rest of the function.

If a block ends with a statement instead of an expression, for example an assignment, the value is Unit (Kotlin's "nothing useful"). val x = if (c) { y = 1 } else { y = 2 } is not a compile error, but x holds Unit. Check what your branches end with.

else is mandatory when you use the value

When if is used as an expression, every possible path must produce a value, so the else branch is required. Without it, the compiler cannot give the variable a value for the false case:

Kotlin if as an expression without else (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with error: 'if' must have both main and 'else' branches when used as an expression.. Add an else, or, if you want the missing case to mean "nothing", use a nullable result: val label: String? = if (n > 3) "big" else null.

As a statement, if without else is fine, because nothing is expected from it.

Mixing branch types

If the branches have different types, the expression has their closest common supertype, which is often Any. That compiles but is rarely what you want:

Kotlin Branches of different types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The throwing branch has the special type Nothing (see Any, Unit and Nothing), which is a subtype of every type. That is why else throw ... or else return ... fits in an expression whose other branch is an Int. This pattern is the core of the "guard clause" style:

Kotlin Early return and throw as expression branches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The final call throws IllegalArgumentException: age cannot be negative: -1 and ends the program, which is the point of a guard clause: bad input stops the function early so the rest can assume valid data. The first line of describeAge is a long way of writing age ?: return "age unknown" (see Null Safety).

Conditions and smart casts

Kotlin tracks what a condition proves. After a type test or null check, the compiler treats the variable as the narrower type inside the branch, with no manual cast:

Kotlin Smart casts inside if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice value is Int && value > 100: because && short-circuits, the right side is only evaluated when the left side proved that value is an Int, so value > 100 compiles. Chains like this are much clearer with when, which you will meet next.

Ranges and in checks

Conditions are plain Boolean expressions, so in works nicely with ranges instead of two comparisons joined by &&:

Kotlin Range checks in conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here the else keywords begin a new line. That is allowed inside an expression because the previous line is not a complete expression statement; the compiler keeps reading for the else. Still, many teams format long chains with braces or switch to when.

Style notes

  • Prefer the expression form when you would otherwise declare a var just to set it in each branch.
  • Keep each branch short. If a branch needs ten lines, move it into a function, and the if becomes a clean selector.
  • A function body that is a single if/else is a good fit for the = form: fun abs(n: Int) = if (n < 0) -n else n.
  • Do not nest if expressions more than two levels deep; switch to when or extract functions.
  • There is no "truthy" test: compare explicitly, if (list.isNotEmpty()) or if (text.isNotBlank()), never if (list).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Kotlin code does the same as the Java expression x > 0 ? "pos" : "non-pos"?

    Kotlin has no ternary operator; if is itself an expression, so if (x > 0) "pos" else "non-pos" is the idiom.
  2. 2. What is the value of a block { println("hi"); 42 } used as a branch of an if expression?

    A block used as an expression evaluates to its last expression. println runs first, and 42 is the value.
  3. 3. What happens with val label = if (n > 3) "big" and no else?

    When the value of if is used, every path needs a value, so the else branch is mandatory.
  4. 4. Why does val n = if (ok) 10 else throw IllegalStateException() compile as an Int?

    A throw expression never produces a value and has type Nothing, which fits any expected type, so the whole if has type Int.
  5. 5. What does if (name) do when name is a non-empty String?

    Kotlin has no truthy or falsy values. Write an explicit Boolean, such as name.isNotEmpty().

Summary

  • if can be a statement or an expression; as an expression it needs an else and gives you a value for a val.
  • Kotlin has no ternary operator: write if (c) a else b.
  • A block used as a branch evaluates to its last expression.
  • Branch types unify to a common supertype; throw and return have type Nothing and fit anywhere.
  • Conditions must be real Booleans, and the compiler smart-casts variables after is and null checks.
  • Prefer the expression form for single assignments, keep branches short, and use when for longer chains.

Next: when Expressions