6
Kotlin allows returns for previously declared tags, including implicit labels.
Example of documentation:
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
In that spirit, I would like to make a lambda expression return in advance a fold
.
That is to say:
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 that case I’d like to get 6
(early return of function fold
in 3 + 2 + 1
). However, it seems that the return@fold
is simply returning from the lambda expression and continuing with the fold
normally (result 10 = 3 + 2 + 1 + 4
).
Is there any way to make that early return?
This language feature looks pretty cool, I don’t know almost anything yet but I like Kotlin. This would be something like
yield
? Expression lambida :D– Maniero
I’m also trying to explore. I liked it a lot (a good middle ground between Scala and Java). It seems they have plans to support
yield
officially in the future. This is more to Labels on Steroids :).– Anthony Accioly
@mustache, I only saw the expression "lick" now hehehe. Thanks.
– Anthony Accioly