Kotlin allows returns for previously declared tags , including implicit tags.
Documentation example:
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
In this spirit, I would like to make a lambda expression return in advance a fold
.
This is:
val array = intArrayOf(3, 2, 1, 4)
val firstEvenSum = array.fold(0, {acc, n ->
val sum = acc + n
if (sum % 2 == 0)
return@fold sum
sum
})
println("First even sum is: $firstEvenSum")
In this case I would like to get 6
(early return of the fold
function in 3 + 2 + 1
). However, it seems that return@fold
is simply returning the lambda expression and continuing with fold
normally (result 10 = 3 + 2 + 1 + 4
).
Is there any way to make this early return?