0
0
KotlinHow-ToBeginner · 3 min read

How to Use withIndex in Kotlin: Simple Guide with Examples

In Kotlin, withIndex() is used on collections to get a sequence of IndexedValue objects containing both the index and the value. You can loop over this sequence to access each element's index and value together easily.
📐

Syntax

The withIndex() function is called on an iterable collection like a list or array. It returns a sequence of IndexedValue objects, each holding an index and a value.

Typical usage in a for loop looks like this:

  • for ((index, value) in collection.withIndex()) { ... }
kotlin
for ((index, value) in collection.withIndex()) {
    // use index and value
}
💻

Example

This example shows how to use withIndex() to print each element of a list with its index.

kotlin
fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    for ((index, fruit) in fruits.withIndex()) {
        println("Fruit at index $index is $fruit")
    }
}
Output
Fruit at index 0 is Apple Fruit at index 1 is Banana Fruit at index 2 is Cherry
⚠️

Common Pitfalls

One common mistake is trying to use withIndex() without destructuring the IndexedValue. For example, using for (item in collection.withIndex()) and then trying to access item as a value directly will not work as expected.

Always destructure the pair into index and value or access item.index and item.value explicitly.

kotlin
fun main() {
    val numbers = listOf(10, 20, 30)

    // Wrong way - will print IndexedValue objects
    for (item in numbers.withIndex()) {
        println(item) // prints IndexedValue(index=0, value=10) etc.
    }

    // Right way - destructure to index and value
    for ((index, value) in numbers.withIndex()) {
        println("Index: $index, Value: $value")
    }
}
Output
IndexedValue(index=0, value=10) IndexedValue(index=1, value=20) IndexedValue(index=2, value=30) Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30
📊

Quick Reference

  • withIndex(): Returns a sequence of IndexedValue objects from a collection.
  • IndexedValue: Holds index and value properties.
  • Use destructuring in for loops: for ((index, value) in collection.withIndex()).
  • Can be used with arrays, lists, and other iterables.

Key Takeaways

Use withIndex() to get both index and value when looping over collections.
Destructure the IndexedValue in the loop with (index, value) for easy access.
withIndex() works on lists, arrays, and other iterable collections.
Avoid treating the IndexedValue as a simple value without destructuring.
It simplifies code when you need element positions alongside values.