Bird
0
0

In Kotlin, when iterating over a list with withIndex(), what does the loop variable represent?

easy📝 Conceptual Q1 of 15
Kotlin - Loops and Ranges
In Kotlin, when iterating over a list with withIndex(), what does the loop variable represent?
AOnly the element at the current index
BA pair containing the current index and the element at that index
COnly the current index without the element
DA map of all indices to their elements
Step-by-Step Solution
Solution:
  1. Step 1: Understand withIndex()

    The withIndex() function returns an Iterable of IndexedValue objects, each containing an index and the corresponding element.
  2. Step 2: Loop variable unpacking

    In a for loop, you can destructure this into two variables: one for the index and one for the value.
  3. Final Answer:

    A pair containing the current index and the element at that index -> Option B
  4. Quick Check:

    withIndex() returns index-element pairs [OK]
Quick Trick: withIndex() returns index and value pairs [OK]
Common Mistakes:
MISTAKES
  • Assuming withIndex() returns only values
  • Thinking withIndex() returns a map
  • Using only index without value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes