Beginner: Kotlin · Kotlin basics · topic 3 of 50 · 25 min
Conditions: if and when
Explanation
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.
| Operator | Meaning | Example |
|---|---|---|
| ==, != | equal, not equal | city == "Pune" |
| <, >, <=, >= | less, greater, or equal | age >= 18 |
| && | and: both must be true | age >= 18 && hasId |
| || | or: at least one true | isAdmin || isOwner |
| ! | not: flips true and false | !isBlocked |
if, else if, else
fun main() {
val marks = 72
if (marks >= 75) {
println("Distinction")
} else if (marks >= 33) {
println("Pass")
} else {
println("Fail")
}
}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.
val orderTotal = 349
val deliveryFee = if (orderTotal >= 199) 0 else 30
println("Delivery: Rs $deliveryFee") // Delivery: Rs 0when: 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.
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
}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.
fun fare(age: Int, isStudent: Boolean): Int = when {
age < 5 -> 0
age >= 60 -> 40
isStudent -> 50
else -> 100
}Checking types with is
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"
}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
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.)
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
}Practice (0/3 done)
What does this print? val score = 45 val result = when { score >= 90 -> "A" score >= 60 -> "B" score >= 40 -> "C" else -> "F" } println(result)
Why does this not compile? val fee = if (isMember) 0
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops and rangesKotlin basics · same module
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- Decisions with if and switchGo Programming (backend and cloud) · Control flow and functions
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Control flow: if, loop, while and forRust Programming · Types, control flow and functions
Questions people ask about this
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.
How many branches of if / else if / else can run?Related
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.
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.
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 more topic in “Kotlin basics” before its exam: Loops and ranges.
- Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.