Challenge - 5 Problems
When Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of when expression with multiple conditions
What is the output of this Kotlin code using
when expression?Kotlin
val x = 7 val result = when (x) { in 1..5 -> "Small" in 6..10 -> "Medium" else -> "Large" } println(result)
Attempts:
2 left
💡 Hint
Check which range the value 7 belongs to.
✗ Incorrect
The value 7 falls in the range 6..10, so the when expression returns "Medium".
❓ Predict Output
intermediate2:00remaining
When expression with type checking
What will be printed by this Kotlin code using
when with type checks?Kotlin
fun describe(obj: Any): String = when (obj) { is String -> "String of length ${obj.length}" is Int -> "Integer: $obj" else -> "Unknown" } println(describe("Hello"))
Attempts:
2 left
💡 Hint
Look at the type of the argument passed to describe.
✗ Incorrect
The argument is a String "Hello" with length 5, so the when expression returns "String of length 5".
🔧 Debug
advanced2:00remaining
Identify the error in when expression with missing else
What error will this Kotlin code produce?
Kotlin
val y = 3 val output = when (y) { 1 -> "One" 2 -> "Two" else -> "Unknown" } println(output)
Attempts:
2 left
💡 Hint
Check if all possible values of y are covered.
✗ Incorrect
The when expression is not exhaustive and lacks an else branch, so Kotlin reports a compilation error.
❓ Predict Output
advanced2:00remaining
When expression with complex conditions
What is the output of this Kotlin code using
when with complex conditions?Kotlin
val num = 15 val category = when { num % 3 == 0 && num % 5 == 0 -> "FizzBuzz" num % 3 == 0 -> "Fizz" num % 5 == 0 -> "Buzz" else -> "None" } println(category)
Attempts:
2 left
💡 Hint
Check divisibility of 15 by 3 and 5.
✗ Incorrect
15 is divisible by both 3 and 5, so the first condition matches and returns "FizzBuzz".
❓ Predict Output
expert2:00remaining
When expression with smart casting and variable assignment
What will be the output of this Kotlin code using
when with smart casting and variable assignment?Kotlin
fun process(input: Any) { val result = when (input) { is String -> input.length is Int -> input * 2 else -> -1 } println(result) } process("Kotlin")
Attempts:
2 left
💡 Hint
What is the length of the string "Kotlin"?
✗ Incorrect
The input is a String "Kotlin" with length 6, so the when expression returns 6.