Explain it simply
Explain it simply
This lesson teaches no new syntax. It is a workout for the basics chapter: val and var, when, loops and null safety. You write each answer yourself, run it, and only then compare it with the reference solution below.
Think of learning to ride a bicycle. Reading about balance helps a little, but you really learn on the bicycle, and the bruises show you the exact spots where you lose control. In this set the bruises are boundary values: the number that is equal, zero, an empty list, a null. For every task, first predict the output on paper, then run it, then try one boundary value on purpose.
Problem → Why → Solution
The problem: it prints plausible output and is still wrong
The first attempt at these tasks usually compiles and prints believable output for the sample data, so it feels correct. The draft below hides two bugs: the FizzBuzz conditions are in the wrong order, and the odd-number test uses % 2 == 1.
Run it and 15 prints Fizz instead of FizzBuzz, because the i % 3 branch is tested first and when picks the first branch that matches. The odd counter reports 0 odd numbers in -4, -3 and 2, because in Kotlin the remainder takes the sign of the dividend, so -3 % 2 is -1 and never equals 1. Neither bug shows up if you only try 1 to 14 and positive numbers.
fun main() {
for (i in 14..15) {
val word = when {
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
i % 15 == 0 -> "FizzBuzz"
else -> i.toString()
}
println("$i -> $word")
}
val numbers = listOf(-4, -3, 2)
var odd = 0
for (n in numbers) if (n % 2 == 1) odd++
println("odd count: $odd, and -3 % 2 is ${-3 % 2}")
}Why does the compiler say nothing?
Both lines are valid Kotlin. A when with overlapping conditions is legal, because the language simply takes the first match, and % is defined for negative numbers too. The compiler checks that code is well formed, not that it means what you meant. The only defence is a habit: test the boundaries, meaning the first and last value, zero, a negative and the empty case, before you call a task finished.
Core concept: one trap per task
Each of the four tasks pairs one idea from the basics chapter with one trap. Knowing the trap before you start typing saves most of the debugging time, so read these four notes first and write your own answers afterwards.
Task 1: when without a subject
A when { ... } with conditions checks them from top to bottom and runs the first one that is true. Because it is used as an expression whose value becomes the function's result, every possible input must produce something, so the else branch handles the equal case. Writing equality as else, instead of a third condition, guarantees that no pair of numbers is left uncovered.
Task 2: order conditions from specific to general
A number divisible by 15 is also divisible by 3 and by 5, so the 15 test has to come first. The range from..to is empty when from is greater than to, so fizzBuzz(5, 3) returns an empty list without any special code. Zero is divisible by everything, so fizzBuzz(0, 0) correctly gives FizzBuzz, which surprises people the first time they see it.
Task 3: null is not empty
text?.length has the type Int? and is null when the receiver is null. The empty string is a real value with length 0, so it must not print no value. The chain ?.length?.toString() ?: "no value" keeps the type String all the way: the second ?. runs only when there is a length, and ?: supplies the fallback. Without toString(), the Elvis expression would have the type Any, which is legal but loses information.
Task 4: loops, remainders and an empty total
A while loop needs three things: a counter, a condition and the line that advances the counter, and forgetting index++ makes it run forever. sum starts at 0, the neutral element of addition, so an empty list returns 0 without a special case. numbers[index] % 2 == 0 recognises negative even numbers too, because -4 % 2 is 0, while a test such as % 2 == 1 misses negative odd numbers.
| Task | Boundary to try | Expected |
|---|---|---|
| Compare | Equal numbers | The equal message |
| FizzBuzz | 0, 15 and from > to | FizzBuzz, FizzBuzz, empty list |
| Null safety | null versus empty string | no value versus 0 |
| Sum of evens | Empty list, negatives | 0 and a negative sum |
- Predict the output on paper
- Run and compare
- Try one boundary value
- Fix, then re-run everything
A wrong prediction points at the part you have not understood yet.
General pattern
val label = when {
first > second -> "first"
first < second -> "second"
else -> "equal"
}
for (i in from..to) { /* most specific condition first */ }
val text = value?.length?.toString() ?: "fallback"
var index = 0
while (index < list.size) { /* use list[index] */ index++ }Cover every case in a when with a final else, put the most specific test first, chain ?. and ?: for nullable values, and always advance the counter in a while loop.
Reference answer: four tasks as functions
The reference solution writes each task as a small function and then exercises it from main with a normal value and at least one boundary value. The inputs are written into the code instead of being read from the keyboard, so every run prints the same lines. Compare it with your own version only after you have finished: names can differ, but the printed results should match.
fun compare(a: Int, b: Int): String = when {
a > b -> "$a is bigger than $b"
a < b -> "$b is bigger than $a"
else -> "$a and $b are equal"
}
fun fizzBuzz(from: Int, to: Int): List<String> {
val words = mutableListOf<String>()
for (i in from..to) {
words += when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> i.toString()
}
}
return words
}
fun lengthOrNone(text: String?): String = text?.length?.toString() ?: "no value"
fun sumOfEvens(numbers: List<Int>): Int {
var index = 0
var sum = 0
while (index < numbers.size) {
if (numbers[index] % 2 == 0) sum += numbers[index]
index++
}
return sum
}
fun main() {
println("Task 1: " + compare(7, 12))
println("Task 1: " + compare(12, 7))
println("Task 1: " + compare(5, 5))
println("Task 2: " + fizzBuzz(1, 20).joinToString(" "))
println("Task 2 (0..0): " + fizzBuzz(0, 0))
println("Task 2 (5..3): " + fizzBuzz(5, 3))
println("Task 3: " + lengthOrNone("Kotlin"))
println("Task 3: " + lengthOrNone(""))
println("Task 3: " + lengthOrNone(null))
println("Task 4: " + sumOfEvens(listOf(3, 8, 12, 5, 20, 7, 6)))
println("Task 4 (empty): " + sumOfEvens(emptyList()))
println("Task 4 (negatives): " + sumOfEvens(listOf(-4, -3, 2)))
}Code breakdown
- Task 1: subject-less when
a > b -> "$a is bigger than $b"Each branch is a condition, an arrow and a value. The strings use $a and $b to insert the numbers, and the else branch below covers equality.
- Task 2: most specific first
i % 15 == 0 -> "FizzBuzz"It sits above the checks for 3 and 5, so 15 is caught before them. i.toString() in the else branch keeps every branch a String, which is what the list needs.
- Task 2: the range
for (i in from..to) {from..to includes both ends and is empty when from is greater than to, so fizzBuzz(5, 3) prints [] and fizzBuzz(0, 0) prints [FizzBuzz].
- Task 3: a nullable chain
fun lengthOrNone(text: String?): String = text?.length?.toString() ?: "no value"null gives no value, the empty string gives 0, and Kotlin gives 6. The result type is String in every case.
- Task 4: loop with a counter
while (index < numbers.size) {The condition is checked before every pass, so an empty list never enters the loop, and the last valid index is size - 1.
- Task 4: the remainder test
if (numbers[index] % 2 == 0) sum += numbers[index]% 2 == 0 recognises -4 as even, which is why the negative list sums to -2 (that is -4 + 2). The index++ line below it is what makes the loop end.
Task 1: 12 is bigger than 7
Task 1: 12 is bigger than 7
Task 1: 5 and 5 are equal
Task 2: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Task 2 (0..0): [FizzBuzz]
Task 2 (5..3): []
Task 3: 6
Task 3: 0
Task 3: no value
Task 4: 46
Task 4 (empty): 0
Task 4 (negatives): -2Remainders and null versus empty, in one run
Two small facts decide most of the bugs in this set: the remainder operator keeps the sign of the left operand, and null and the empty string are different values. Run the snippet and match each printed line with a claim from this lesson.
fun lengthOf(text: String?): Int? = text?.length
fun main() {
println(-4 % 2)
println(-3 % 2)
println(-3 % 3 == 0)
println(0 % 15 == 0)
println(Math.floorMod(-3, 2))
println(lengthOf("Kotlin"))
println(lengthOf(""))
println(lengthOf(null))
}The first four lines show that -4 % 2 is 0, -3 % 2 is -1, and that divisibility tests against 3 and 15 still work for negative numbers and for zero. The fifth line, Math.floorMod(-3, 2), is 1: use it when you need a remainder that is never negative, for example to pick an array index. The last three lines show that Kotlin has length 6, the empty string has length 0, and null has no length at all.
In real projects
In real projects
These four tasks are miniature versions of daily production code. A when with ordered, overlapping conditions is how pricing rules, shipping tiers and permission checks are written, and the ordering bug in FizzBuzz is exactly the bug of a discount rule that never fires because a broader rule sits above it. Null versus empty is the difference between a form field the user never touched and one they cleared, and many APIs treat those two cases differently on purpose.
Remainders and loops appear whenever you page through data, alternate row colours, or spread work over workers with index % workerCount. Negative remainders are a classic source of crashes in code that uses % to pick an array index: -1 % 5 is -1, which is not a valid index, and the fix is floorMod. Finally, the habit this lesson trains, predict first and then test the boundaries, is what code review and automated tests are made of.
Common mistakes
Common mistakes
FizzBuzz conditions in the wrong order
With i % 3 == 0 above i % 15 == 0, the 15 branch can never run, and 15, 30 and 45 print Fizz. Always place the most specific condition first.
Treating null and empty as the same thing
text?.length ?: 0 returns 0 for both, so the caller cannot tell a missing value from an empty one. Decide which behaviour you need, and when the difference matters, print a different message for null, as lengthOrNone does.
Testing odd numbers with % 2 == 1
-3 % 2 is -1, so the test misses negative odd numbers. Test for even with % 2 == 0, or for odd with % 2 != 0.
Forgetting index++ or overflowing an Int
A while loop that never advances its counter runs forever, and an Int sum silently wraps around after 2147483647, so use Long when a total can grow that large.
Best practices
How to practise well
- Spend five to ten minutes on each task before you read the reference solution.
- Write the expected output as comments first, then run and compare.
- For every task add one boundary value on purpose: equal, zero, empty, null or negative.
- Once it works, rewrite the while loop with filter and sum, and compare which version reads best.
Mini challenge
Three new tasks: grades, digit sums and initials
Practise the same skills on three new functions: grade(score) using when with ranges, digitSum(n) using a while loop, and initials(name) using null safety. Test each one on its boundaries.
- grade() returns A for 90 to 100, B for 80 to 89, C for 70 to 79, F for 0 to 69 and invalid for anything else
- digitSum() works for 0, for negative numbers and for Int.MIN_VALUE, using a while loop
- initials() returns the capitalised first letters of each word, and ? for null, empty or blank input
- main prints the boundaries 89 and 90, -1 and 101, 0, -1234, Int.MIN_VALUE, and a null name
fun grade(score: Int): String {
// TODO: when (score) with ranges: in 90..100 -> "A" ... else -> "invalid"
}
fun digitSum(n: Int): Int {
// TODO: while loop; take the last digit with % 10, drop it with / 10
// think about negative numbers and Int.MIN_VALUE before you start
}
fun initials(name: String?): String {
// TODO: split on spaces, ignore blank words, uppercase each first letter
// return "?" when no word is left
}
fun main() {
// TODO: test the boundaries of each function and print the results
}Expected: grade prints A, A, B, C, F, F, invalid and invalid for the eight scores; digitSum prints 0, 11, 10 and 47; initials prints KAZ, MH, S, ?, ? and ?.
Show hint
Ranges work directly in when: in 90..100 -> "A". For digitSum, convert to Long before taking the absolute value, because abs(Int.MIN_VALUE) is still negative. For initials, filter { it.isNotBlank() } removes the empty words that doubled spaces create.
Show solution
import kotlin.math.abs
fun grade(score: Int): String = when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
in 0..69 -> "F"
else -> "invalid"
}
fun digitSum(n: Int): Int {
var rest = abs(n.toLong())
var sum = 0
while (rest > 0) {
sum += (rest % 10).toInt()
rest /= 10
}
return sum
}
fun initials(name: String?): String {
val words = name?.split(" ")?.filter { it.isNotBlank() } ?: emptyList()
if (words.isEmpty()) return "?"
return words.map { it.first().uppercaseChar() }.joinToString("")
}
fun main() {
for (score in listOf(100, 90, 89, 70, 69, 0, -1, 101)) {
println("grade($score) = ${grade(score)}")
}
for (n in listOf(0, 407, -1234, Int.MIN_VALUE)) {
println("digitSum($n) = ${digitSum(n)}")
}
for (name in listOf("ko aung zaw", " Ma Hnin ", "Su", " ", "", null)) {
println("initials($name) = ${initials(name)}")
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Predict the output first, run second, and always try at least one boundary value
- Put the most specific when condition first, and remember that 0 is divisible by everything
- null and the empty string are different values, and ?. and ?: react only to null
- Remainders keep the sign of the dividend, so test evens with % 2 == 0 and start sums at 0
Kotlin language guide — Kotlin