Sequence Builder
Learn about the Kotlin sequence, the need for a builder, and the use of the yield function in Kotlin coroutines.
We'll cover the following
In some other languages, like Python or JavaScript, we can find structures that use limited forms of coroutines:
Async functions (also called async/await).
Generator functions (functions in which subsequent values are yielded).
We’ve already seen how we can use async
in Kotlin, but this will be explained in detail in the "Coroutine Builders" part of the course. Instead of generators, Kotlin provides a sequence builder—a function used to create a sequence. Even better, it offers flow
builders. The concept of Flow
is similar but it's much more powerful, which we'll explain later in the course.
A Kotlin sequence is similar to a collection (like List
or Set
). Still, it's evaluated lazily, meaning the next element is always calculated on demand when needed. As a result, sequences:
Do the minimal number of required operations.
Can be infinite.
Are more memory efficient.
Due to these characteristics, defining a builder where we calculate subsequent elements and “yield” them on demand makes a lot of sense. We define it using the function sequence
. Inside its lambda expression, we can call the yield
function to produce the next elements of this sequence.
Get hands-on with 1200+ tech skills courses.