I'm using the buildSequence
function in Kotlin. How do I end the iteration in the middle of the function? I'm looking for something similar to C#'s yield break
statement.
My code looks something like the following. I'm stuck at the TODO
.
fun foo(list:List<Number>): Sequence<Number> = buildSequence {
if (someCondition) {
// TODO: Bail out early with an empty sequence
// return doesn't seem to work....
}
list.forEach {
yield(someProcessing(it))
}
}
EDIT
Apparently, I misdiagnosed the source. The issue is not returning from the buildSequence
function. The following works for me:
fun foo(list:List<Number>): Sequence<Number> = buildSequence {
return@buildSequence
list.forEach {
yield(someProcessing(it))
}
}
EDIT 2
The issue is that I put the return
in a local helper function that validates data at multiple points in the buildSequence
(Hence the helper function). Apparently I'm not able to return from buildSequence
within the helper function. The error message was not terribly helpful...