Mastering Kotlin: Skipping Iterations with 'foreach'
In the realm of modern programming, Kotlin stands out as a powerful, concise, and expressive language. One of its standout features is the ability to iterate over collections using the 'foreach' loop. However, there might be times when you need to skip certain iterations. Let's delve into how you can achieve this.
Understanding 'foreach' in Kotlin
The 'foreach' loop in Kotlin is a simple and elegant way to iterate over collections. It's defined using the 'for' keyword followed by the element in the collection, then the 'in' keyword, and finally the collection itself. Here's a basic example:
```kotlin val list = listOf(1, 2, 3, 4, 5) for (item in list) { println(item) } ```
Skipping Iterations: The 'continue' Keyword
To skip an iteration, Kotlin provides the 'continue' keyword. When 'continue' is encountered, the loop immediately jumps to the next iteration, skipping the rest of the code in the current iteration. Here's how you can use it to skip even numbers in our previous list:

```kotlin val list = listOf(1, 2, 3, 4, 5) for (item in list) { if (item % 2 == 0) continue // Skip even numbers println(item) } ```
Skipping Remaining Iterations: 'continue' with Label
Sometimes, you might want to skip the rest of the iterations in a loop, not just the current one. You can achieve this by using a label with the 'continue' keyword. Here's an example where we stop printing numbers once we reach 3:
```kotlin outer@ for (item in list) { if (item == 3) continue@outer // Skip remaining iterations once 3 is reached println(item) } ```
Skipping Iterations in Nested Loops
In nested loops, you can use labels to skip iterations in the inner loop. Here's an example where we skip printing numbers that are divisible by both 2 and 3:
```kotlin outer@ for (i in 1..10) { for (j in 1..10) { if (i % 2 == 0 && j % 3 == 0) continue@outer // Skip if both are divisible by 2 and 3 println("$i $j") } } ```
Best Practices and Warnings
- Use 'continue' sparingly: While 'continue' can make your code more concise, overusing it can make your code harder to read and debug.
- Be careful with labels: Labels can make your code more complex. Make sure to use them judiciously and comment your code clearly.
In conclusion, Kotlin's 'foreach' loop, combined with the 'continue' keyword and labeled loops, provides a powerful and flexible way to iterate over collections and skip iterations as needed.























