How to use break and continue inside forEach in Kotlin?
Hello everyone! I just started learning Kotlin and ran into a problem. In other languages, like Java, I'm used to using `break` and `continue` inside `for` or `foreach` loops. But when I tried to do the same in Kotlin inside `forEach`, the compiler gave an error.
Here's an example of code that doesn't work:
```kotlin
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers.forEach { number ->
if (number == 5) {
break // Error: 'break' or 'continue' jumps across a function or a class boundary
}
if (number % 2 == 0) {
continue // Error: similar
}
println(number)
}
```
I expected the loop to stop at number 5 (break) and skip even numbers (continue), but instead I get compilation errors. I understand that `forE
No answers yet.
Log in to leave an answer
Blogs