when Workbook
Practice problems for Kotlin’s when Is the New switch. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
with a subject
1. Day classification
Given day (1–7), return "weekday" for 1–5 and "weekend" for 6–7, using when with a subject and ranges.
Show answer Hide answer
when (day) {
in 1..5 -> "weekday"
in 6..7 -> "weekend"
else -> "invalid"
} 2. Multiple values per branch
Given a Char c, return true when it’s a lowercase vowel, false otherwise.
Show answer Hide answer
when (c) {
'a', 'e', 'i', 'o', 'u' -> true
else -> false
} 3. Assign from a when
Assign size the value "small", "medium", or "large" based on count (< 10, < 100, otherwise), using a subjectless when.
Show answer Hide answer
val size = when {
count < 10 -> "small"
count < 100 -> "medium"
else -> "large"
} type matching
4. Describe an Any
Given x: Any, return "int", "text", or "other" depending on whether it’s an Int, a String, or neither.
Show answer Hide answer
when (x) {
is Int -> "int"
is String -> "text"
else -> "other"
} 5. Use the smart-cast value
Given x: Any, return its length if it’s a String, otherwise 0. Use the smart cast inside the branch.
Show answer Hide answer
when (x) {
is String -> x.length
else -> 0
} ranges and capture
6. Range branches
Given n: Int, return "digit" for 0–9, "teens" for 10–19, else "big".
Show answer Hide answer
when (n) {
in 0..9 -> "digit"
in 10..19 -> "teens"
else -> "big"
} 7. Capture the subject
Rewrite this so the result of readLine() is captured in the when header and reused:
val line = readLine()
when (line) { ... }
Show answer Hide answer
when (val line = readLine()) {
null -> println("no input")
else -> println(line.length)
} exhaustiveness
8. No else for enums
Given enum class Direction { NORTH, SOUTH, EAST, WEST }, write a when expression mapping each to its opposite — with no else branch.
Show answer Hide answer
fun opposite(d: Direction) = when (d) {
Direction.NORTH -> Direction.SOUTH
Direction.SOUTH -> Direction.NORTH
Direction.EAST -> Direction.WEST
Direction.WEST -> Direction.EAST
}Covering every constant makes the when exhaustive, so no else is needed.
9. Replace instanceof + cast
Rewrite this Java-style chain in idiomatic Kotlin:
if (shape is Circle) return shape.radius
if (shape is Square) return shape.side
Show answer Hide answer
when (shape) {
is Circle -> shape.radius
is Square -> shape.side
else -> 0.0
} 10. Statement, not expression
Write a when that just prints a message for each level (1, 2, else) — used as a statement, returning nothing.
Show answer Hide answer
when (level) {
1 -> println("low")
2 -> println("high")
else -> println("unknown")
} Back to the lesson, Kotlin’s when Is the New switch, or on to the next one: smart casts.
Comments