Kotlin Exercises
Time to practise. Each exercise has a starter playground that already compiles and runs — the parts you need to write are marked with TODO. Edit the code, press ▶ Run, and compare your result with the expected output in the task description. Try for real before opening a solution: the struggle is where the learning happens.
Tip: The output block under each starter shows what the unfinished starter prints. The task text tells you what the finished program should print.
Exercise 1: FizzBuzz with when
For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Use a when expression. Expected: 1, 2, Fizz, 4, Buzz, …, 14, FizzBuzz, one per line.
fun main() {
for (i in 1..15) {
val text = i.toString() // TODO: use when to choose Fizz/Buzz/FizzBuzz
println(text)
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
fun main() {
for (i in 1..15) {
val text = when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> i.toString()
}
println(text)
}
}The % 15 branch must come first: when picks the first matching branch, and 15 is also divisible by 3.
Exercise 2: Palindromes
Write isPalindrome(text: String): Boolean that ignores case, spaces and punctuation. Expected output:
racecar: true
Kotlin: false
A man, a plan, a canal: Panama: truefun isPalindrome(text: String): Boolean {
// TODO: keep only letters/digits, lowercase them, compare with the reversed string
return false
}
fun main() {
for (s in listOf("racecar", "Kotlin", "A man, a plan, a canal: Panama")) {
println("$s: ${isPalindrome(s)}")
}
}racecar: false
Kotlin: false
A man, a plan, a canal: Panama: false
Show solution
fun isPalindrome(text: String): Boolean {
val clean = text.filter { it.isLetterOrDigit() }.lowercase()
return clean == clean.reversed()
}
fun main() {
for (s in listOf("racecar", "Kotlin", "A man, a plan, a canal: Panama")) {
println("$s: ${isPalindrome(s)}")
}
}filter on a String returns a new String containing only the characters for which the lambda is true.
Exercise 3: Word frequencies
Count how often each word appears in the text (case-insensitive) and print the three most frequent words with their counts, most frequent first (ties: alphabetical). Expected output:
the: 4
cat: 2
on: 2fun main() {
val text = "The cat sat on the mat. The dog sat on the cat"
val words = text.lowercase().split(" ", ".").filter { it.isNotEmpty() }
println(words.size)
// TODO: count words with groupingBy { it }.eachCount() (or groupBy), sort, take 3, print
}12
Show solution
fun main() {
val text = "The cat sat on the mat. The dog sat on the cat"
val words = text.lowercase().split(" ", ".").filter { it.isNotEmpty() }
words.groupingBy { it }.eachCount()
.entries
.sortedWith(compareByDescending<Map.Entry<String, Int>> { it.value }.thenBy { it.key })
.take(3)
.forEach { (word, count) -> println("$word: $count") }
}groupingBy { it }.eachCount() builds a Map<String, Int> in one step. "sat" also appears twice, but "cat" and "on" win the alphabetical tie-break.
Exercise 4: Safe parsing with null safety
The list contains user input. Convert every entry to an Int, treating invalid entries as missing. Print the valid numbers, how many were invalid, and their sum. Don't use !! or try. Expected output:
Valid: [12, 7, 30]
Invalid: 2
Sum: 49fun main() {
val input = listOf("12", "seven", "7", "", "30")
val valid = listOf<Int>() // TODO: use mapNotNull with toIntOrNull
println("Valid: $valid")
println("Invalid: ${input.size - valid.size}")
println("Sum: ${valid.sum()}")
}Valid: []
Invalid: 5
Sum: 0
Show solution
fun main() {
val input = listOf("12", "seven", "7", "", "30")
val valid = input.mapNotNull { it.toIntOrNull() }
println("Valid: $valid")
println("Invalid: ${input.size - valid.size}")
println("Sum: ${valid.sum()}")
}toIntOrNull() returns null for text that isn't a number, and mapNotNull drops those nulls.
Exercise 5: A data class with copy
Complete the Book data class with a function borrow() that returns a copy with available = false (or throws IllegalStateException with the message "<title> is already borrowed" if it isn't available — use check). Expected output:
Book(title=Dune, author=Herbert, available=false)
Error: Dune is already borroweddata class Book(val title: String, val author: String, val available: Boolean = true) {
fun borrow(): Book {
// TODO: check availability, then return a copy
return this
}
}
fun main() {
val borrowed = Book("Dune", "Herbert").borrow()
println(borrowed)
try {
borrowed.borrow()
} catch (e: IllegalStateException) {
println("Error: ${e.message}")
}
}Book(title=Dune, author=Herbert, available=true)
Show solution
data class Book(val title: String, val author: String, val available: Boolean = true) {
fun borrow(): Book {
check(available) { "$title is already borrowed" }
return copy(available = false)
}
}
fun main() {
val borrowed = Book("Dune", "Herbert").borrow()
println(borrowed)
try {
borrowed.borrow()
} catch (e: IllegalStateException) {
println("Error: ${e.message}")
}
}Exercise 6: Shapes with a sealed interface
Add a Triangle(base, height) case and complete area with an exhaustive when (no else). Print each area with one decimal. Expected output:
Circle: 12.6
Square: 9.0
Triangle: 6.0sealed interface Shape
data class Circle(val r: Double) : Shape
data class Square(val side: Double) : Shape
// TODO: add Triangle
fun area(s: Shape): Double = when (s) {
is Circle -> Math.PI * s.r * s.r
is Square -> s.side * s.side
}
fun main() {
val shapes = listOf(Circle(2.0), Square(3.0))
for (s in shapes) println("${s::class.simpleName}: ${"%.1f".format(area(s))}")
}Circle: 12.6
Square: 9.0
Show solution
sealed interface Shape
data class Circle(val r: Double) : Shape
data class Square(val side: Double) : Shape
data class Triangle(val base: Double, val height: Double) : Shape
fun area(s: Shape): Double = when (s) {
is Circle -> Math.PI * s.r * s.r
is Square -> s.side * s.side
is Triangle -> s.base * s.height / 2
}
fun main() {
val shapes = listOf(Circle(2.0), Square(3.0), Triangle(4.0, 3.0))
for (s in shapes) println("${s::class.simpleName}: ${"%.1f".format(area(s))}")
}If you add Triangle but forget the branch, the compiler reports that the when is not exhaustive — that's the point of sealed types.
Exercise 7: An extension function
Write an extension function List<Int>.stats(): String that returns "min=…, max=…, avg=…" (average with one decimal), or "empty" for an empty list. Expected output:
min=3, max=19, avg=9.8
empty// TODO: fun List<Int>.stats(): String = ...
fun main() {
val a = listOf(8, 3, 19, 9)
val b = emptyList<Int>()
println(a.size)
println(b.size)
}4
0
Show solution
fun List<Int>.stats(): String =
if (isEmpty()) "empty"
else "min=${min()}, max=${max()}, avg=${"%.1f".format(average())}"
fun main() {
val a = listOf(8, 3, 19, 9)
val b = emptyList<Int>()
println(a.stats())
println(b.stats())
}Inside the extension, isEmpty(), min() and average() are called on the receiver list — no this. needed.
Exercise 8: Higher-order retry
Write fun <T> retry(times: Int, block: (attempt: Int) -> T?): T? that calls block with attempt numbers 1, 2, 3… until it returns a non-null value or times attempts are used up. Expected output:
attempt 1
attempt 2
attempt 3
Result: connected on attempt 3
attempt 1
attempt 2
Result: nullfun <T> retry(times: Int, block: (attempt: Int) -> T?): T? {
// TODO: loop from 1 to times, return the first non-null result
return null
}
fun main() {
val r1 = retry(5) { n ->
println("attempt $n")
if (n == 3) "connected on attempt $n" else null
}
println("Result: $r1")
val r2 = retry(2) { n -> println("attempt $n"); null }
println("Result: $r2")
}Result: null
Result: null
Show solution
fun <T> retry(times: Int, block: (attempt: Int) -> T?): T? {
for (attempt in 1..times) {
val result = block(attempt)
if (result != null) return result
}
return null
}
fun main() {
val r1 = retry(5) { n ->
println("attempt $n")
if (n == 3) "connected on attempt $n" else null
}
println("Result: $r1")
val r2 = retry(2) { n -> println("attempt $n"); null }
println("Result: $r2")
}The generic type T is inferred from the lambda: String in the first call. In the second call the lambda only returns null, so T becomes Nothing, and the result prints as null.
Where next?
When these feel comfortable, move on to the Mini Project, where you build a small library manager step by step, combining classes, collections, null safety and sealed results.
Test yourself
Which call turns listOf("1", "x", "3") into [1, 3]?
- map { it.toInt() }
- mapNotNull { it.toIntOrNull() }
- filter { it.toInt() }
- map { it.toIntOrNull() }
What does listOf("a", "b", "a").groupingBy { it }.eachCount() return?
- {a=2, b=1}
- [2, 1]
- {a=[a, a], b=[b]}
- 3