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

bookLooping with Indices

Deslize para mostrar o 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?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 4

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 2. Capítulo 4
some-alt