0
0
Kotlinprogramming~20 mins

When as expression returning value 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 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)
AThree
BTwo
COne
DUnknown
Attempts:
2 left
💡 Hint
Check which case matches the value of x.
Predict Output
intermediate
2: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)
ALow
BSyntax Error
CHigh
DMedium
Attempts:
2 left
💡 Hint
Look at the range that includes 5.
Predict Output
advanced
2: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"))
AInteger value Hello
BString of length 5
CUnknown type
DCompilation error
Attempts:
2 left
💡 Hint
Check the type of the argument passed to describe.
Predict Output
advanced
2: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)
AMedium
BSmall
CLarge
DRuntime exception
Attempts:
2 left
💡 Hint
Check which condition matches the value 100.
Predict Output
expert
2: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)
AType: Int, Value: 84
BType: String, Value: "42"
CType: Any?, Value: null
DType: Int, Value: 42
Attempts:
2 left
💡 Hint
Look at the type of input and what each branch returns.