July 2018
Intermediate to advanced
242 pages
8h 6m
English
The basic variant of the generateSequence() function is declared as follows:
fun <T : Any> generateSequence(nextFunction: () -> T?): Sequence<T>
It takes one parameter called nextFunction, which is a function that returns the next elements of the sequence. Under the hood, it is being invoked by the Iterator.next() function, inside the Sequence class' internal implementation, and allows instantiation of the next object to be returned while consuming the sequence values.
In the following example, we are going to implement a finite sequence that emits integers from 10 to 0:
var counter = 10val sequence: Sequence<Int> = generateSequence { counter--.takeIf { value: Int -> value >= 0 }}print(sequence.toList())
The takeIf() function ...
Read now
Unlock full access