Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q14 of 15
Kotlin - Loops and Ranges
Identify the error in this Kotlin code snippet:
val numbers = arrayOf(10, 20, 30)
for (i, num in numbers.withIndex()) {
    println("$i -> $num")
}
ACannot use withIndex() on arrays.
BMissing parentheses around (i, num) in the for loop.
CThe println statement syntax is incorrect.
DVariable names i and num are reserved keywords.
Step-by-Step Solution
Solution:
  1. Step 1: Check for correct destructuring syntax

    In Kotlin, destructuring pairs in a for loop requires parentheses: for ((i, num) in ...).
  2. Step 2: Verify other parts of the code

    Using withIndex() on arrays is valid. The println syntax and variable names are correct.
  3. Final Answer:

    Missing parentheses around (i, num) in the for loop. -> Option B
  4. Quick Check:

    Destructure pairs with parentheses [OK]
Quick Trick: Always use parentheses to destructure pairs in for loops [OK]
Common Mistakes:
MISTAKES
  • Omitting parentheses in destructuring
  • Thinking withIndex() doesn't work on arrays
  • Misreading println syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes