In Kotlin, if you want to obtain the current index of each element while iterating over a collection, you can use the withIndex() function. This function returns an iterator that provides an object containing both the index and value on each iteration.
For example, suppose we have a list of strings and we want to print each string along with its position in the list. The code can be written as follows:
kotlinval fruits = listOf("Apple", "Banana", "Cherry", "Date") for ((index, fruit) in fruits.withIndex()) { println("Index: $index, Fruit: $fruit") }
In this example, the withIndex() function allows simultaneous access to both the index (index) and the value (fruit) through the IndexedValue data structure. This enables direct usage within the loop without manually incrementing the index.
This approach not only makes the code more concise but also reduces the likelihood of errors, as the index management is automatically handled by the withIndex() function.