Let's consider an example, where you are able to generate the next element of the sequence, but you do not see an easy way to implement a Java iterator.
fun fibonacci() = sequence {
var a_0 = 1
var a_1 = 1
// this sequence is infinite
while(true) {
val a_n = a_0 + a_1
a_0 = a_1
a_1 = a_n
//this is a suspend function call
yield(a_0)
}
}
The example uses the yield
function to return the next element of the sequence. The function is an example of a suspend
function in Kotlin. The call to the function suspends the execution of the sequence{..}
block, so the call stack is free.
Let's say we do the following
fibonacci().take(10).forEach{
println(it)
}
Every iteration of the forEach
loop will resume the sequence{..}
block from the previous yield
function call and let it run to the next yield
function call. The execution flow will mix the forEach
loop iterations with the sequence{..}
block evaluation. You may try writing the same as Java Iterator
to feel what Kotlin compiler does behind the scenes.
suspend
functions in Kotlin are done minimalistic on the language and the standard library side, the rest can be implemented in libraries. I recommend checking the kotlinx.coroutines
library for more insides, examples, and documentation
https://github.com/Kotlin/kotlinx.coroutines