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 returning a value
What is the output of this Kotlin code using
when as an expression?Kotlin
val x = 3 val result = when (x) { 1 -> "One" 2 -> "Two" 3 -> "Three" else -> "Unknown" } println(result)
Attempts:
2 left
💡 Hint
Check which case matches the value of x.
✗ Incorrect
The variable x is 3, so the when expression returns "Three".
❓ Predict Output
intermediate2:00remaining
When expression with multiple matching conditions
What will this Kotlin code print?
Kotlin
val y = 5 val output = when (y) { in 1..4 -> "Low" in 5..10 -> "Medium" else -> "High" } println(output)
Attempts:
2 left
💡 Hint
Look at the range that includes 5.
✗ Incorrect
The value 5 falls in the range 5..10, so the when expression returns "Medium".
❓ Predict Output
advanced2:00remaining
When expression with smart casting and return value
What is the output of this Kotlin code?
Kotlin
fun describe(obj: Any): String { return when (obj) { is String -> "String of length ${obj.length}" is Int -> "Integer value $obj" else -> "Unknown type" } } println(describe("Hello"))
Attempts:
2 left
💡 Hint
Check the type of the argument passed to describe.
✗ Incorrect
The argument is a String "Hello". The when expression smart casts it to String and returns its length.
❓ Predict Output
advanced2:00remaining
When expression with no matching branch and else clause
What will this Kotlin code print?
Kotlin
val z = 100 val result = when (z) { in 1..10 -> "Small" in 11..50 -> "Medium" else -> "Large" } println(result)
Attempts:
2 left
💡 Hint
Check which condition matches the value 100.
✗ Incorrect
100 does not fall in 1..10 or 11..50, so the else branch returns "Large".
❓ Predict Output
expert2:30remaining
When expression returning different types and type inference
What is the type and value of
result after running this Kotlin code?Kotlin
val input: Any = 42 val result = when (input) { is Int -> input * 2 is String -> input.length else -> 0 } println(result)
Attempts:
2 left
💡 Hint
Look at the type of input and what each branch returns.
✗ Incorrect
The input is an Int 42, so the when expression returns 42 * 2 = 84. The inferred type is Int.