Bird
0
0

What is the issue with this Kotlin code snippet?

medium📝 Debug Q6 of 15
Kotlin - Loops and Ranges
What is the issue with this Kotlin code snippet?
val letters = listOf("x", "y", "z")
for (i, letter in letters.withIndex()) {
  println("$i: $letter")
}
AThe list should be converted to an array before using withIndex()
BThe loop variable should be destructured using parentheses: (i, letter)
CwithIndex() cannot be used with lists
DThe println statement syntax is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop variable syntax

    In Kotlin, when destructuring a pair or IndexedValue in a for loop, parentheses are required around the variables.
  2. Step 2: Identify the error

    The code uses for (i, letter in ...) instead of for ((i, letter) in ...), which causes a syntax error.
  3. Final Answer:

    The loop variable should be destructured using parentheses: (i, letter) -> Option B
  4. Quick Check:

    Destructuring requires parentheses [OK]
Quick Trick: Destructure pairs with parentheses in for loops [OK]
Common Mistakes:
MISTAKES
  • Omitting parentheses in destructuring
  • Trying to use withIndex() on unsupported types
  • Incorrect println syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes