Bird
0
0

Identify the problem in this Kotlin code:

medium📝 Debug Q7 of 15
Kotlin - Control Flow as Expressions
Identify the problem in this Kotlin code:
val y = 15
val res = when (y) {
  in 1..10 -> "Low"
  in 11..20 -> "Medium"
  in 21..30 -> "High"
}
println(res)
AMissing else branch causes compilation error
BRanges are incorrect
CVariable y is not initialized
DNo problem, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check completeness of when expression

    When expression with argument must be exhaustive or have else branch.
  2. Step 2: No else branch and not all values covered

    Values outside 1..30 are not covered, so else is required.
  3. Final Answer:

    Missing else branch causes compilation error -> Option A
  4. Quick Check:

    Exhaustive when needs else branch = Missing else branch causes compilation error [OK]
Quick Trick: Add else branch if when is not exhaustive [OK]
Common Mistakes:
MISTAKES
  • Omitting else branch in non-exhaustive when
  • Incorrect range boundaries
  • Assuming default else is implicit

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes