You can think of yield()
as “return, and next time start from where you stopped“:
val sequence = sequence {
val start = 0
yield(start) // first return
yieldAll(1..5 step 2) // if called again, will start from here
yieldAll(generateSequence(8) { it * 3 }) // if called more that six times, start from here
}
It creates state machine and stuff, but you can translate it to something like following in Java:
class Seq {
private AtomicInteger count = new AtomicInteger(0);
private int state = 0;
public int nextValue() {
if (count.get() == 0) {
return state;
}
else if (count.get() >= 1 && count.get() <= 5) {
state += 2;
return state;
}
else {
state *= 3;
return state;
}
}
}
In Java class we maintain explicit state by having two variables: count
and state
. Combination of sequence
and yield
allow this state to be maintained implicitly.
Note that yield()
is a suspending function, so it may be invoked only from another suspend
function or from within a coroutine.