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

bookLooping with Indices

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  4
some-alt