2

I can use continue in normal for loop.

for (i in 0..10) {
    // .. some initial code
    if (i == something) continue
    // .. some other code
}

But it seems I can't use it in forEach

(0 .. 10).forEach {
    // .. some initial code
    if (i == something) continue
    // .. some other code
}

Is there a way to use have the similar continue statement for forEach?

Mosius
  • 1,602
  • 23
  • 32
Elye
  • 53,639
  • 54
  • 212
  • 474

2 Answers2

4

From the source code for forEach :

@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

For every element of the collection a lambda method action is applied. So, in order to go the next element in your for loop the lambda method must finish. And to finish it return but in scope of @forEach must be called:

(0 .. 10).forEach {
    // .. some initial code
    if (i = something) {
        return@forEach
    }
    // .. some other code
}
Anatolii
  • 14,139
  • 4
  • 35
  • 65
0

Use return@forEach instead of continue

Mosius
  • 1,602
  • 23
  • 32