Bird
0
0

Find the error in this Kotlin code snippet: val x = 3 when (x) { 1, 2 -> println("Low") 3 && 4 -> println("Medium") else -> println("High") }

medium📝 Debug Q6 of 15
Kotlin - Control Flow as Expressions
Find the error in this Kotlin code snippet: val x = 3 when (x) { 1, 2 -> println("Low") 3 && 4 -> println("Medium") else -> println("High") }
AUsing '&&' instead of commas in when conditions
BMissing else branch
CIncorrect variable declaration
DUsing println inside when
Step-by-Step Solution
Solution:
  1. Step 1: Identify invalid syntax in when conditions

    The condition '3 && 4' uses logical AND, which is invalid syntax in when branches.
  2. Step 2: Correct usage of multiple conditions

    Multiple values should be separated by commas, not logical operators.
  3. Final Answer:

    Using '&&' instead of commas in when conditions -> Option A
  4. Quick Check:

    Use commas, not logical operators, in when conditions = D [OK]
Quick Trick: Replace logical operators with commas in when conditions [OK]
Common Mistakes:
MISTAKES
  • Using && or || instead of commas
  • Thinking else branch is mandatory error
  • Confusing println usage as error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes