Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Conditional Expressions and Loops  ›  Lesson

if as an Expression

if 12 minIn Kotlin, if is an expression that produces a value, so it replaces the ternary operator, and when it is used for a value it must have an else branch.

if as an Expression

The café's receipt should say "Thanks, regular!" for loyal customers and "Welcome!" for everyone else. In many languages you would declare a variable, then fill it in from two branches. In Kotlin, if itself hands back the answer.

The rule

if returns a value; with a value comes an else.

The familiar statement form still works:

if (cups >= 10) {
    println("Free drink!")
}

But if is also an expression: it produces the value of whichever branch runs.

val greeting = if (visits >= 10) "Thanks, regular!" else "Welcome!"

This is why Kotlin has no ternary operator (cond ? a : b). An if on one line does the same job.

When a branch is a block { }, its value is the last expression in the block:

val price = if (isMember) {
    println("Member discount applied")
    3.5 * 0.9          // this is the value: 3.15
} else {
    3.5
}

Chains work with else if, checked from top to bottom; the first true condition wins:

val label = if (visits >= 10) "regular"
            else if (visits >= 3) "returning"
            else "new"

When you use if for a value, the else is required. Without it, some paths would produce nothing, and the compiler rejects the code. As a plain statement, else is optional.

The shortcut

Read an if expression as "this value, when …, otherwise that value". For chains, test the most demanding condition first, then check that the final else catches everything left over.

Labelling a customer with 12 visitsStep 1 of 4
  1. First condition

    visits >= 10: 12 is at least 10, so this is true.

Drills

Answer fast — trust the rule.

quick drill

What is val x = if (4 > 7) "yes" else "no"?

quick drill

Why does val tip = if (total > 20) 2.0 fail to compile?

quick drill

How do you write "a if cond else b" in Kotlin?

quick drill

What is the value of if (true) { println("hi"); 5 } else { 0 }?

quick drill

With visits = 5, what does if (visits >= 3) "returning" else if (visits >= 5) "loyal" else "new" give?

Remember

  • if is an expression; it replaces the ternary operator.
  • A block's value is its last expression; a value-producing if needs else.
  • In chains, the first true condition wins: most demanding first.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLabel a customer

Customers with 10 or more visits are "regular", those with 3 to 9 are "returning", and everyone else is "new". Write this as a single val label = … using if, explain why Kotlin needs no ternary operator, and explain why removing the final else breaks the code.