Recall & Review
beginner
What does the
withIndex() function do in a Kotlin for loop?It allows you to loop over a collection while accessing both the index and the value of each element at the same time.
Click to reveal answer
beginner
How do you access the index and value inside a
for loop using withIndex()?You can use destructuring syntax:
for ((index, value) in collection.withIndex()) where index is the position and value is the element.Click to reveal answer
intermediate
Why is using
withIndex() better than manually managing an index variable in a loop?Because it is cleaner, less error-prone, and Kotlin handles the index automatically, so you don’t have to update it yourself.
Click to reveal answer
beginner
Write a simple Kotlin
for loop using withIndex() to print each index and value from a list of fruits.Example:<br>
val fruits = listOf("Apple", "Banana", "Cherry")<br>for ((index, fruit) in fruits.withIndex()) {<br> println("Fruit at index $index is $fruit")<br>}Click to reveal answer
beginner
Can
withIndex() be used with arrays and other collections in Kotlin?Yes,
withIndex() works with arrays, lists, and any iterable collection to provide index-value pairs.Click to reveal answer
What does
withIndex() return when called on a list?✗ Incorrect
withIndex() returns a sequence of pairs where each pair contains the index and the corresponding value from the list.
How do you write a
for loop to get both index and value from a list items?✗ Incorrect
Option B uses destructuring to get both index and value from withIndex().
Which of these is a benefit of using
withIndex() in Kotlin loops?✗ Incorrect
withIndex() helps you get index and value easily without managing an index variable yourself.
What happens if you use
for (index in list.withIndex()) without destructuring?✗ Incorrect
Without destructuring, the loop variable is a pair containing both index and value.
Can
withIndex() be used with arrays in Kotlin?✗ Incorrect
withIndex() works with arrays, lists, and other iterable collections.
Explain how to use
withIndex() in a Kotlin for loop to access both index and value.Think about how you get both position and element in the loop.
You got /4 concepts.
Why is using
withIndex() preferred over manually incrementing an index variable in loops?Consider what problems manual index management can cause.
You got /4 concepts.