Bird
0
0

Find the error in this Kotlin when expression:

medium📝 Debug Q6 of 15
Kotlin - Control Flow as Expressions
Find the error in this Kotlin when expression:
val z: Any = 10
val result = when (z) {
  in 1..5 -> "Small"
  in 6..10 -> "Medium"
  is String -> "Text"
  else -> "Unknown"
}
AThe ranges 1..5 and 6..10 cannot be used with Any type.
BThere is no error; the code is correct.
CThe <code>when</code> expression is missing an else branch.
DThe <code>when</code> expression mixes range and type checks incorrectly.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze type compatibility with ranges

    Ranges check if value is in range; since z is Any but holds Int 10, range checks work.
  2. Step 2: Check mixing of range and type checks in when

    Kotlin allows mixing range and type checks in when expressions.
  3. Final Answer:

    There is no error; the code is correct. -> Option B
  4. Quick Check:

    Mixing ranges and types in when is allowed = C [OK]
Quick Trick: You can mix range and type checks in when expressions [OK]
Common Mistakes:
MISTAKES
  • Thinking Any type disallows range checks
  • Believing else branch is mandatory if type checks exist
  • Assuming mixing ranges and types causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes