Comprehensive Guide to forEachIndexed in Kotlin: Accessing Loop Indices

Nov 23, 2025 · Programming · 8 views · 7.8

Keywords: Kotlin | forEachIndexed | Loop Indices

Abstract: This technical article provides an in-depth exploration of the forEachIndexed method in Kotlin programming language. It covers various techniques for accessing loop indices, compares different approaches including traditional for loops, indices method, and withIndex method, and offers complete code examples with best practices for effective Kotlin development.

Overview of Loop Index Access in Kotlin

In Kotlin programming, accessing the current index position while iterating through collection elements is a common requirement. Unlike traditional languages like Java, Kotlin provides multiple elegant approaches for handling loop indices, with the forEachIndexed method standing out as the most direct and feature-complete solution.

Detailed Explanation of forEachIndexed Method

forEachIndexed is a higher-order function provided in Kotlin's standard library for collection types, introduced since Kotlin 1.0. This method accepts a lambda expression as a parameter, which includes two arguments: the index and the element value. The method signature is as follows:

inline fun <T> Iterable<T>.forEachIndexed(
    action: (index: Int, T) -> Unit
): Unit

In practical usage, it can be invoked as follows:

val collection = listOf("A", "B", "C", "D")
collection.forEachIndexed { index, element ->
    println("Index: $index, Element: $element")
}

This code will output:

Index: 0, Element: A
Index: 1, Element: B
Index: 2, Element: C
Index: 3, Element: D

Solving Specific Problems: Performing Operations Every Second Iteration

To address the user's requirement of "performing specific operations every second iteration," we can combine forEachIndexed with modulo operation:

val numbers = listOf(10, 20, 30, 40, 50, 60)
numbers.forEachIndexed { index, value ->
    if (index % 2 == 0) {
        println("Iteration ${index + 1}, Value: $value")
        // Perform other operations
    }
}

In this code, the condition index % 2 == 0 ensures that specific operations are executed only at even index positions (i.e., 1st, 3rd, 5th... iterations).

Comparative Analysis with Other Methods

Traditional For Loop Approach

Although Kotlin supports traditional for loop syntax, forEachIndexed offers a more functional programming style:

// Traditional approach
for (i in collection.indices) {
    val element = collection[i]
    if (i % 2 == 0) {
        // Processing logic
    }
}

// forEachIndexed approach
collection.forEachIndexed { i, element ->
    if (i % 2 == 0) {
        // Processing logic
    }
}

Comparison with withIndex Method

withIndex is another method for accessing indices, returning IndexedValue objects:

for ((index, value) in collection.withIndex()) {
    if (index % 2 == 0) {
        println("Element at position $index: $value")
    }
}

Compared to forEachIndexed, withIndex feels more natural in for loops, while forEachIndexed integrates better in functional programming chains.

Performance Considerations and Best Practices

When selecting index access methods in practical development, consider the following factors:

Advanced Application Scenarios

forEachIndexed excels in complex business logic scenarios, for example:

data class User(val name: String, val age: Int)

val users = listOf(
    User("Alice", 25),
    User("Bob", 30),
    User("Charlie", 35)
)

users.forEachIndexed { index, user ->
    when {
        index % 2 == 0 -> println("User at even position: ${user.name}")
        user.age > 30 -> println("Senior user: ${user.name}")
        else -> println("Other user: ${user.name}")
    }
}

Conclusion

forEachIndexed, as the standard method for handling loop indices in Kotlin, provides a concise, safe, and feature-complete solution. By properly utilizing this method, developers can write more elegant and maintainable Kotlin code, particularly in scenarios requiring simultaneous access to both indices and element values.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.