Mastering Kotlin's Foreach with Index: A Comprehensive Guide
In the realm of modern programming, Kotlin's concise and expressive syntax has made it a popular choice for Android app development and server-side applications. One of its powerful features is the `forEachIndexed` function, which allows you to iterate over a collection with both its index and value. Let's dive into the world of `foreachIndexed` and explore its capabilities.
Understanding Kotlin's ForeachIndexed
`forEachIndexed` is an extension function provided by Kotlin's standard library. It takes a lambda function as an argument, which is invoked for each element in the collection. The lambda function has two parameters: the index of the element (starting from 0) and the element itself. This enables you to perform operations that require both the index and the value of the elements.
Syntax and Signature
The syntax for `forEachIndexed` is as follows:

collection.forEachIndexed { index, element ->
// Your code here
}
The signature of the lambda function is `(Int, T) -> Unit`, where `Int` represents the index, `T` is the type of the elements in the collection, and `Unit` signifies that the function doesn't return any value.
Why Use ForeachIndexed?
You might wonder why you would use `forEachIndexed` when the regular `forEach` function can iterate over a collection as well. The key difference lies in the additional index parameter provided by `forEachIndexed`. This allows you to perform tasks that require knowing the index of an element, such as:
- Replacing elements at specific indices.
- Printing or logging the index and value of each element.
- Creating a new collection with modified elements based on their indices.
Examples of ForeachIndexed in Action
Printing Index and Value
Let's start with a simple example that prints the index and value of each element in a list:

val list = listOf("Apple", "Banana", "Cherry")
list.forEachIndexed { index, fruit ->
println("Index: $index, Fruit: $fruit")
}
This will output:
Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Cherry
Replacing Elements
Now let's see how to replace elements at specific indices. Suppose we want to replace the first and last elements of a list with an exclamation mark:
val list = mutableListOf("Apple", "Banana", "Cherry")
list.forEachIndexed { index, fruit ->
if (index == 0 || index == list.lastIndex) {
list[index] = "!"
}
}
After running this code, `list` will be `["!", "Banana", "!"]`.

Creating a New Collection
You can also use `forEachIndexed` to create a new collection based on the indices and values of the original collection. For instance, let's create a new list that contains only the fruits whose names have an even number of characters:
val list = listOf("Apple", "Banana", "Cherry")
val newList = mutableListOf()
list.forEachIndexed { index, fruit ->
if (fruit.length % 2 == 0) {
newList.add(fruit)
}
}
After running this code, `newList` will be `["Banana"]`.
Performance Considerations
While `forEachIndexed` is a powerful tool, it's essential to consider its performance implications. Since it iterates over the entire collection, using it in a tight loop can lead to performance issues. In such cases, consider using more efficient data structures or algorithms tailored to your specific use case.
Conclusion
Kotlin's `forEachIndexed` function is a versatile tool that enables you to perform operations requiring both the index and value of elements in a collection. By mastering `forEachIndexed`, you can write more expressive and concise code, making your Kotlin applications more powerful and maintainable. Happy coding!






















