Question
Understanding Kotlin's yield function
I don't see a very clear definition of the yield
function in Kotlin.
Example in the link above doesn't mention much but the following,
val sequence = sequence {
val start = 0
// yielding a single value
yield(start)
// yielding an iterable
yieldAll(1..5 step 2)
// yielding an infinite sequence
yieldAll(generateSequence(8) { it * 3 })
}
println(sequence.take(7).toList()) // [0, 1, 3, 5, 8, 24, 72]
But the above example doesn't point out the significance of yield.
- What does it mean that it is a suspending function?
- In what scenarios can it be advantageous?