1. if as an expression
In Kotlin, if is an expression — it returns a value. You can assign that value, return it, or pass it directly:
val max = if (a > b) a else b
Multi-line bodies work too — the last expression of the chosen branch is the value:
val label = if (score >= 50) {
println("nice work")
"pass"
} else {
"fail"
}
2. Use if as an expression
Implement larger(a, b) returning whichever is bigger. Write it in a single line: return if (a > b) a else b.
Starter code
fun larger(a: Int, b: Int): Int {
return 0
}3. when expressions
when is the switch-on-steroids. It's also an expression — every branch produces a value:
val label = when (n) {
1 -> "one"
2, 3 -> "few"
else -> "many"
}
Drop the subject to write boolean conditions in each branch — useful for ranges, guards, anything:
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "F"
}
4. Use when
Implement letterGrade(score):
- 90 or above →
"A" - 80 to 89 →
"B" - 70 to 79 →
"C" - below 70 →
"F"
Use when { ... } (no subject) with boolean conditions.
Starter code
fun letterGrade(score: Int): String {
return ""
}5. if vs when — when to use which
Both are conditional expressions. The choice is mostly readability:
| Pattern | Reach for… |
|---|---|
| Two branches based on a single boolean | if |
| Three or more branches, or matching multiple values / ranges | when |
// "if" is fine here:
val out = if (active) "on" else "off"
// "when" is much cleaner here:
val tier = when {
score >= 90 -> "gold"
score >= 70 -> "silver"
score >= 50 -> "bronze"
else -> "none"
}
Anything you can write with chained if/else if you can usually rewrite with when — and when exhausts cleanly.
6. FizzBuzz with when
The classic. Implement fizzBuzz(n):
- divisible by both 3 and 5 →
"FizzBuzz" - divisible by 3 →
"Fizz" - divisible by 5 →
"Buzz" - otherwise →
n.toString()
Use a subjectless when { ... } — each branch is condition -> value and the condition must be a Boolean. So write n % 3 == 0, not just n % 3 (which is an Int and the compiler will reject it).
Order matters: check divisibility by 15 first, otherwise a multiple of 15 will match the % 3 branch and never reach "FizzBuzz".
return when {
n % 15 == 0 -> "FizzBuzz"
// …fill in the rest
else -> n.toString()
}
Starter code
fun fizzBuzz(n: Int): String {
return when {
// each branch is: Boolean -> String
// e.g. n % 15 == 0 -> "FizzBuzz"
else -> n.toString()
}
}Run this Kotlin lesson in your browser
SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.
Sign in to run this code →