0
0
Kotlinprogramming~20 mins

When expression as powerful switch in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
When Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
ASmall
BLarge
CMedium
DCompilation error
Attempts:
2 left
💡 Hint
Check which range the value 7 belongs to.
Predict Output
intermediate
2: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"))
AInteger: Hello
BString of length 5
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Look at the type of the argument passed to describe.
🔧 Debug
advanced
2: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)
ACompilation error: 'when' expression must be exhaustive
BRuntime exception: No matching branch found
CPrints null
DPrints "One"
Attempts:
2 left
💡 Hint
Check if all possible values of y are covered.
Predict Output
advanced
2: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)
ANone
BFizz
CBuzz
DFizzBuzz
Attempts:
2 left
💡 Hint
Check divisibility of 15 by 3 and 5.
Predict Output
expert
2: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")
A6
B12
CCompilation error
D-1
Attempts:
2 left
💡 Hint
What is the length of the string "Kotlin"?