Looping with Indices
Swipe to show menu
When you need to access both the index and the value of elements in a list or array during a loop in Kotlin, you can use the withIndex() function. This function is available on collections and arrays, and it allows you to iterate through each element while also keeping track of its position. This is especially useful when you want to display or process both the index and the value together in your logic.
Main.kt
In the example above, the withIndex() function is called on the fruits list. This returns an iterable of IndexedValue objects, each containing an index and a value. When you use the syntax for ((index, value) in fruits.withIndex()), Kotlin automatically unpacks each IndexedValue into its index and value components for you. On each loop iteration, index holds the current position in the list, and value holds the element at that position. This approach is concise and eliminates the need for manual index tracking, making your code easier to read and less error-prone.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat