Kotlin If...Else and when
Control flow should make a decision traceable. Kotlin lets if and when produce values directly, which removes temporary mutable state and keeps every allowed branch near the rule that selects it. Begin with simple boolean conditions, then use when for a known set of values or state shapes; make invalid input and fallback behavior intentional.
Work through the examples in order. Each one changes only one idea at a time, so you can connect the code you write to the output you see. Do not skip the changed-input step: that is where syntax becomes a dependable programming habit.
What You Will Build
This page is a compact code lab, not a one-paragraph definition. The five examples move from the smallest valid form to a boundary case or reusable function. Keep a local Kotlin compiler open while reading: type each example, make the suggested change, and observe the output before continuing.
In real software, the same discipline protects larger systems. Name inputs clearly, validate data at the boundary, avoid logging secrets, and make an error or alternate result visible to the caller. Kotlin's syntax helps, but the programmer still owns the business rule.
Example 1: Simple if...else
An if...else branch chooses exactly one path based on a Boolean condition. Name the predicate so the reader understands the rule before reading either branch.
Kotlin
fun main() {
val score = 72
if (score >= 60) {
println("pass")
} else {
println("retry")
}
}
Expected Result
pass
Try next: Run with 59 and 60. Those values prove the boundary condition instead of only proving a comfortable normal case.
Read the example in order: identify the input, trace the Kotlin expression or branch, then compare the printed result with the stated rule. A small change should produce a predictable new result; if it does not, make the contract explicit before adding more syntax.
Example 2: if as an expression
Kotlin if can return a value, so a branch can create one result without declaring a mutable variable first. This is useful when the decision is local and each branch has the same return meaning.
Kotlin
fun gradeLabel(score: Int): String =
if (score >= 90) "excellent" else "continue"
fun main() {
println(gradeLabel(91))
}
Expected Result
excellent
Try next: Add a validation branch for scores outside 0 through 100 before classifying a value.
Read the example in order: identify the input, trace the Kotlin expression or branch, then compare the printed result with the stated rule. A small change should produce a predictable new result; if it does not, make the contract explicit before adding more syntax.
Example 3: when with exact values
when is clear when one input maps to a finite list of exact cases. Keep the fallback explicit so an unsupported value does not quietly look like a known result.
Kotlin
fun dayType(day: Int): String = when (day) {
1, 7 -> "weekend"
2, 3, 4, 5, 6 -> "weekday"
else -> "invalid"
}
fun main() {
println(dayType(1))
}
Expected Result
weekend
Try next: Try 0 and 8. An invalid result should be visible to the caller instead of becoming a believable default.
Read the example in order: identify the input, trace the Kotlin expression or branch, then compare the printed result with the stated rule. A small change should produce a predictable new result; if it does not, make the contract explicit before adding more syntax.
Example 4: when with conditions
when without an argument can express ordered conditions such as ranges. Put invalid or exceptional conditions first, then move from the most specific valid case to the broad fallback.
Kotlin
fun shipping(days: Int): String = when {
days < 0 -> "invalid"
days == 0 -> "today"
days <= 2 -> "soon"
else -> "scheduled"
}
fun main() {
println(shipping(2))
}
Expected Result
soon
Try next: Trace every input around the edges: -1, 0, 1, 2, and 3. Check that no condition shadows the one below it.
Read the example in order: identify the input, trace the Kotlin expression or branch, then compare the printed result with the stated rule. A small change should produce a predictable new result; if it does not, make the contract explicit before adding more syntax.
Example 5: Return early for invalid input
An early return protects the valid path from being nested under several conditions. Once invalid input is rejected, the rest of the function can describe the normal result using non-ambiguous state.
Kotlin
fun discount(total: Int): Int {
if (total < 0) return 0
return total / 10
}
fun main() {
println(discount(250))
}
Expected Result
25
Try next: Decide whether a negative total should return 0, throw an error, or be impossible by construction. The correct choice belongs to the caller contract.
Read the example in order: identify the input, trace the Kotlin expression or branch, then compare the printed result with the stated rule. A small change should produce a predictable new result; if it does not, make the contract explicit before adding more syntax.
Example 6: Make the input visible
Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Replace the sample value with one from your own notes, predict the result, and then run it.
Example 7: Guard an empty boundary
A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.
Example 8: Keep the transformation pure
This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.
Example 9: Make a branch deliberate
Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Change the boundary value by one and explain exactly which branch becomes active.
Example 10: Use a collection without hidden mutation
Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Add one more item and predict the derived result before executing the code.
Example 11: Return a named outcome
A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Rename the outcome in your own words while preserving the same success and failure rule.
Example 12: Trace a small loop
Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.
Example 13: Keep display at the edge
The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Change only the display text and verify that the underlying rule and result stay unchanged.
Example 14: Test the closest boundary
A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Try the lowest supported value and then one value just outside the accepted range.
Example 15: Write a tiny regression check
A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Kotlin If...Else and when.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Kotlin
fun review(value: String?): String =
value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
?: "needs a value"
fun main() {
println(review("Kotlin If Else and when"))
}Expected Result
KOTLIN IF ELSE AND WHEN
Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.
Practice Checklist
A tutorial becomes useful only when you can produce the behavior without copying the last code block. Complete the five short repetitions below, then write one new version that uses your own names and values.
- Practice 1: reproduce “Simple if...else” from memory, change one input, and explain the result before running it.
- Practice 2: reproduce “if as an expression” from memory, change one input, and explain the result before running it.
- Practice 3: reproduce “when with exact values” from memory, change one input, and explain the result before running it.
- Practice 4: reproduce “when with conditions” from memory, change one input, and explain the result before running it.
- Practice 5: reproduce “Return early for invalid input” from memory, change one input, and explain the result before running it.
For a stronger check, explain one invalid input and the response the caller should receive. A generic crash, an unlabelled default, or a printed error is not a complete failure contract.
Common Mistakes
- Copying a code block without changing an input, then assuming the rule is understood.
- Using a convenient fallback where the caller actually needs a validation error, retry state, or explicit missing result.
- Hiding mutable state, external work, or an exception behind a short expression that a future reader cannot safely review.
- Treating type inference as a reason to hide an important numeric range, nullable value, or public API contract.
