Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Looping with Indices | Working with Ranges and Collections
Kotlin Loops

bookLooping 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

Main.kt

copy

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.

question mark

What does the withIndex() function provide when looping through a collection?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 4
some-alt