Creating Infinite Sequences

We'll cover the following

Since coroutines are useful for creating cooperating tasks, we can use them to create an infinite series or unbounded values and process the generated values at the same time. A function may create a value in the series and yield it to the code that is expecting the value. Upon consuming the value, the calling code can come back asking for the next value in the series. These steps can continue in tandem until either the code that produces the series exits or the caller doesn’t bother asking for another value in the series. We’ll take a look at two different functions available in Kotlin to create infinite series.

Using sequence

The Kotlin library has a sequence function that’s readily available for creating a series of values. We’ll use that to create an infinite series of prime numbers, starting from a given number.

Here’s a primes() function that takes a starting number and returns a Sequence<Int>. The Sequence acts as a continuation, yielding values for iteration.

Get hands-on with 1200+ tech skills courses.