"Mastering Kotlin: foreachIndexed Example for Looping with Index"

Mastering Kotlin: The Power of foreachIndexed

In the realm of modern programming, Kotlin, a statically-typed programming language, has gained significant traction due to its concise syntax and improved interoperability with Java. One of its powerful features is the `foreachIndexed` function, which allows you to iterate over a collection with both the element and its index. Let's dive into an example that demonstrates its usage and benefits.

Understanding the Basics

The `foreachIndexed` function is an extension function provided by the Kotlin Standard Library. It allows you to iterate over a collection in a concise and readable manner, providing you with both the element at the current index and the index itself. This can be particularly useful when you need to perform operations that require the index, such as modifying the original collection or working with paired indices and elements.

Kotlin foreachIndexed Example

Let's consider an example where we have a list of strings, and we want to print each string along with its index, but only if the string starts with the letter 'K'. Here's how you can achieve this using `foreachIndexed`:

Kotlin
Kotlin

```kotlin val fruits = listOf("Apple", "Banana", "Kiwi", "Mango", "Kumquat") fruits.withIndex().foreachIndexed { index, (fruit, _) -> if (fruit.startsWith('K')) { println("Fruit at index $index is $fruit") } } ```

In this example, `withIndex()` is used to get a sequence of pairs, where each pair consists of an element from the original list and its index. The `foreachIndexed` function then iterates over these pairs, providing us with the index and the element (in this case, a pair of index and fruit).

Modifying the Original Collection

One of the benefits of using `foreachIndexed` is that it allows you to modify the original collection based on the index. For instance, you can remove elements at specific indices. Here's an example:

```kotlin val numbers = mutableListOf(1, 2, 3, 4, 5) numbers.foreachIndexed { index, number -> if (number % 2 == 0) { numbers.removeAt(index) } } ```

In this example, we're iterating over the `numbers` list and removing each even number. However, we need to be careful when modifying the collection while iterating over it. In this case, we're using `removeAt(index)`, which modifies the list by removing the element at the specified index. If we were to use a simple `for` loop, we would need to adjust the index after each removal to account for the shifted indices.

The Most Underrated Kotlin Function
The Most Underrated Kotlin Function

Use Cases and Best Practices

  • Use when you need the index: `foreachIndexed` is particularly useful when you need to perform operations that require the index, such as modifying the original collection or working with paired indices and elements.
  • Avoid modifying the collection when possible: While `foreachIndexed` allows you to modify the original collection, it's generally a good practice to avoid modifying collections while iterating over them. It can make your code more difficult to read and reason about, and it can lead to unexpected behavior or bugs.
  • Consider using other iteration functions: Depending on your use case, other iteration functions like `forEach`, `map`, `filter`, or `reduce` might be more appropriate. Each of these functions has its own strengths and use cases, so it's important to choose the right tool for the job.

In conclusion, the `foreachIndexed` function is a powerful tool in the Kotlin programmer's toolbox. It allows you to iterate over a collection with both the element and its index, enabling a wide range of use cases. However, like any powerful tool, it should be used judiciously and with an understanding of its potential pitfalls.

5 Untold Features of Kotlin
5 Untold Features of Kotlin
Mastering Inline Functions in Kotlin: Understanding inline, noinline, crossinline, and reified type
Mastering Inline Functions in Kotlin: Understanding inline, noinline, crossinline, and reified type
Kotlin — Using When
Kotlin — Using When
Easy caching Android + Kotlin + Flow
Easy caching Android + Kotlin + Flow
Programming with Result: kotlin.Result
Programming with Result: kotlin.Result
the text toying with kotlin's next receiver by nicholas frankel may,
the text toying with kotlin's next receiver by nicholas frankel may,
Exploring Kotlin Inline Properties
Exploring Kotlin Inline Properties
Mastering in Kotlin Generics and Variance
Mastering in Kotlin Generics and Variance
a poster with the words, branches and merges in git
a poster with the words, branches and merges in git
the nginx website has been updated to provide users with their own content and information
the nginx website has been updated to provide users with their own content and information
a black background with yellow text and an image of a man in the middle of it
a black background with yellow text and an image of a man in the middle of it
UI & Design System Capabilities
UI & Design System Capabilities
a poster with different types of correlations and their corresponding numbers on it
a poster with different types of correlations and their corresponding numbers on it
the kubernets networking diagram
the kubernets networking diagram
an image of what is capacitance? in this graphic, you can see the
an image of what is capacitance? in this graphic, you can see the
the 32 ways you're underusingt clave code info sheet is shown
the 32 ways you're underusingt clave code info sheet is shown
an info sheet with different types of web pages
an info sheet with different types of web pages
a man standing in front of a blackboard with the words css comments on it
a man standing in front of a blackboard with the words css comments on it
two palm trees are silhouetted against an orange and pink sky at sunset on the water
two palm trees are silhouetted against an orange and pink sky at sunset on the water
Concurrency vs Parallelism
Concurrency vs Parallelism
Every Networking Concept Explained | Networking 101 (2026)
Every Networking Concept Explained | Networking 101 (2026)
rshiny explainer by Kalielifl
rshiny explainer by Kalielifl
breadth first search algorithm
breadth first search algorithm