Skip to content

Beginner: Kotlin · Kotlin basics · topic 3 of 50 · 25 min

Conditions: if and when

Explanation

if runs code only when a condition is true, and in Kotlin it is an expression, so it can give a value: val fee = if (member) 0 else 50. when is Kotlin's powerful replacement for switch: it checks a value against several options, ranges or types, and can also be used as an expression with an else branch.

Making decisions

Programs often need to choose: show "Pass" or "Fail", charge delivery or not, allow login or not. A condition is a question with a true or false answer, like marks >= 33. Kotlin uses if for simple choices and when for many choices.

OperatorMeaningExample
==, !=equal, not equalcity == "Pune"
<, >, <=, >=less, greater, or equalage >= 18
&&and: both must be trueage >= 18 && hasId
||or: at least one trueisAdmin || isOwner
!not: flips true and false!isBlocked

if, else if, else

kotlin
fun main() {
    val marks = 72
    if (marks >= 75) {
        println("Distinction")
    } else if (marks >= 33) {
        println("Pass")
    } else {
        println("Fail")
    }
}
Conditions are checked from top to bottom; the first true one runs. Prints Pass.

The braces after if hold the code to run. If there is only one line, you may leave the braces out, but many teams keep them anyway because adding a second line later without braces is a classic bug.

if as an expression

In Kotlin, if gives back a value, so you can use it on the right side of =. This is why Kotlin has no ? : ternary operator like Java. When used this way, else is required, so every case produces a value.

kotlin
val orderTotal = 349
val deliveryFee = if (orderTotal >= 199) 0 else 30
println("Delivery: Rs $deliveryFee")   // Delivery: Rs 0
The value of the chosen branch is stored in deliveryFee.

when: many choices

when compares a value with several branches. It is clearer than a long chain of else if. Each branch is condition -> result. else catches everything else.

kotlin
fun main() {
    val day = 6
    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3, 4, 5 -> "Midweek"        // several values in one branch
        in 6..7 -> "Weekend"         // a range
        else -> "Invalid day"
    }
    println(name)                    // Weekend
}
in 6..7 checks whether day is between 6 and 7, both included.

when without an argument

You can also write when with no value after it. Then each branch is a full condition, and the first true one wins. This is a clean replacement for if-else chains.

kotlin
fun fare(age: Int, isStudent: Boolean): Int = when {
    age < 5 -> 0
    age >= 60 -> 40
    isStudent -> 50
    else -> 100
}
Bus fare rules read almost like plain English.

Checking types with is

kotlin
fun describe(x: Any): String = when (x) {
    is Int -> "a number: ${x + 1}"     // x is treated as Int here (smart cast)
    is String -> "text of length ${x.length}"
    else -> "something else"
}
Any is the parent of all Kotlin types. After is Int, Kotlin smart-casts x to Int automatically.
Think of it like this: when is like the sorting desk at a post office. Each letter (value) is checked against the labels: Delhi pin codes go to tray 1, Mumbai to tray 2, a range of pin codes to tray 3, and anything unknown goes to the "others" tray (else).

Common mistakes

  • Writing if (x = 5) instead of if (x == 5). = assigns, == compares; Kotlin rejects the first.
  • Forgetting else when using if or when as an expression: "if must have both main and else branches if used as an expression".
  • Long else-if ladders. Switch to when for readability.
  • Wrong order of conditions: checking marks >= 33 before marks >= 75 means nobody gets Distinction. Put the strictest condition first.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Conditions: if and when · 1/6

age >= 18 city == "Pune"

Programs make decisions with conditions: questions with a true or false answer.

Prefer a video by a teacher? Find free videos on “kotlin if else when expression tutorial” on YouTube ↗

In real life: Electricity bill slabs

State electricity boards charge different rates per unit for different slabs of usage. A when with ranges expresses the slabs clearly, and changing a rate later means editing one line. (The rates below are made up for practice.)

kotlin
fun ratePerUnit(units: Int): Double = when (units) {
    in 0..100 -> 3.0
    in 101..300 -> 5.0
    in 301..500 -> 7.0
    else -> 8.5
}

fun main() {
    val units = 250
    println("Rate: Rs ${ratePerUnit(units)} per unit")   // Rate: Rs 5.0 per unit
}
A simplified model: real bills apply each slab rate only to the units inside that slab.

Practice (0/3 done)

Task 1 · Question

What does this print? val score = 45 val result = when { score >= 90 -> "A" score >= 60 -> "B" score >= 40 -> "C" else -> "F" } println(result)

Task 2 · Question

Why does this not compile? val fee = if (isMember) 0

Task 3 · Practice

Write fun ticketPrice(age: Int, isWeekend: Boolean): Int for a water park: under 3 free, 3 to 12 pay 300, 60 and above pay 350, everyone else pays 500, and add 100 on weekends for everyone who pays. Use when, and test it with 5 different calls.

Quick quiz

Question 1

1.What does && mean?

Question 2

2.Which Kotlin feature replaces Java's switch statement?

Question 3

3.What does in 10..20 check in a when branch?

Question 4

4.What is a smart cast?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does && mean?

Answer: Both conditions are true

&& is logical AND.

Which Kotlin feature replaces Java's switch statement?

Answer: when

when is Kotlin's flexible branching construct.

What does in 10..20 check in a when branch?

Answer: The value is between 10 and 20, both included

A range check including both ends.

What is a smart cast?

Answer: Kotlin automatically treating a value as a type after an is check

After is Int, the compiler lets you use the value as an Int.

What does _ mean in a switch expression?Related

Answer: Match anything else (the discard)

The discard pattern _ matches any value not matched earlier.

From Decisions: if, else, switch and switch expressions

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

How do you make one switch case match both 1 and 2?Related

Answer: case 1, 2:

List several values separated by commas in one case.

From Decisions with if and switch

Which type can NOT be used in a switch?Related

Answer: std::string

switch needs an integral or enum value. Use if / else if for strings.

From Operators and decisions: if, else and switch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Kotlin basics” before its exam: Loops and ranges.
  2. Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.

← Previous: First program, val and var, and types