0
0
Kotlinprogramming~20 mins

When with multiple conditions in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
When Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of when with multiple conditions combined by commas
What is the output of this Kotlin code snippet?
Kotlin
fun main() {
    val x = 3
    val result = when (x) {
        1, 2 -> "One or Two"
        3, 4 -> "Three or Four"
        else -> "Other"
    }
    println(result)
}
AThree or Four
BCompilation error
COne or Two
DOther
Attempts:
2 left
💡 Hint
Remember that commas separate multiple matching values in a when branch.
Predict Output
intermediate
2:00remaining
When with condition ranges and multiple conditions
What will this Kotlin program print?
Kotlin
fun main() {
    val score = 85
    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89, 75 -> "B"
        else -> "C"
    }
    println(grade)
}
ARuntime exception
BB
CC
DA
Attempts:
2 left
💡 Hint
Check if the score matches any of the conditions including the single value 75.
🔧 Debug
advanced
2:00remaining
Identify the error in when with multiple conditions
What error does this Kotlin code produce?
Kotlin
fun main() {
    val y = 5
    val output = when (y) {
        1, 2 -> "Low"
        3, 4 -> "Medium"
        else -> "High"
    }
    println(output)
}
ANo error, prints "Medium"
BTypeError: Cannot compare Int with Int
CSyntaxError: Missing comma between 3 and 4
DRuntimeException: Unreachable code
Attempts:
2 left
💡 Hint
Look carefully at the syntax between 3 and 4 in the when expression.
Predict Output
advanced
2:00remaining
When with multiple conditions and else branch
What is the output of this Kotlin code?
Kotlin
fun main() {
    val input = "apple"
    val category = when (input) {
        "banana", "orange" -> "Citrus"
        "apple", "pear" -> "Pome"
        else -> "Unknown"
    }
    println(category)
}
APome
BUnknown
CCitrus
DCompilation error
Attempts:
2 left
💡 Hint
Check which branch matches the input string.
🧠 Conceptual
expert
2:00remaining
How does Kotlin's when handle multiple conditions?
Which statement best describes how Kotlin's when expression handles multiple conditions separated by commas in a single branch?
AAll conditions separated by commas must be true simultaneously for the branch to match.
BMultiple conditions separated by commas cause a compilation error.
CThe branch matches only if the subject matches the first condition and ignores the rest.
DThe branch matches if the subject equals any one of the listed conditions separated by commas.
Attempts:
2 left
💡 Hint
Think about how commas work in a when branch.