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

bookLooping with Indices

Pyyhkäise näyttääksesi valikon

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?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 4

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 4
some-alt