How to use break and continue inside forEach in Kotlin?
Hi everyone! I started learning Kotlin and encountered an unexpected problem. When I write a regular `for` loop, I can freely use `break` and `continue`:
```kotlin
for (i in 1..10) {
if (i == 5) break
if (i % 2 == 0) continue
println(i)
}
```
But as soon as I try to do the same inside `forEach`:
```kotlin
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers.forEach { i ->
if (i == 5) break // Compilation error!
if (i % 2 == 0) continue // Also an error!
println(i)
}
```
The compiler gives an error: "break and continue are only allowed inside a loop". I understand that `forEach` is not a loop, but a higher-order function that takes a lambda. But I need to somehow break execution or skip an iteration. Please tell me how to do this.
No answers yet.
Log in to leave an answer
Blogs
Docker and C#: Containerizing .NET Applications from Scratch
Introduction to Kotlin in 2025: A Complete Guide for Beginners
A/B Testing in PHP: How to Stop Guessing and Start Earning
* and Any in Kotlin: What's the Difference and Which to Choose? Breakdown with Examples