Avatar ·

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.