Bird
0
0

Find the error in this Kotlin code using when without argument:

medium📝 Debug Q14 of 15
Kotlin - Control Flow as Expressions
Find the error in this Kotlin code using when without argument:
val y = 3
val result = when {
  y > 5 -> println("Greater than 5")
  y < 5 -> println("Less than 5")
}
AMissing else branch for unmatched cases
BIncorrect use of parentheses after when
CConditions must be constants, not expressions
DCannot use println inside when
Step-by-Step Solution
Solution:
  1. Step 1: Check when branches

    The code has two conditions but no else branch to handle all other cases.
  2. Step 2: Understand Kotlin requirement

    When used without argument, Kotlin requires an else branch to cover all possibilities or the compiler errors about non-exhaustive when.
  3. Final Answer:

    Missing else branch for unmatched cases -> Option A
  4. Quick Check:

    Always add else branch [OK]
Quick Trick: Always include else branch in when without argument [OK]
Common Mistakes:
MISTAKES
  • Ignoring else branch requirement
  • Adding parentheses after when
  • Thinking conditions must be constants

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes