How it works...
We used takeWhile, which returns a sequence containing first elements satisfying the given predicate (in this case, i<data[i]).
Though takeWhile returns the first elements that satisfy the given predicate, you might be tempted to think that it will first evaluate the complete range and then pass to forEach. That would have been the case if we hadn't used .asSequence(). We converted the range to a Sequence<T>, and because of this, it was lazily evaluated. In short, it won't process the whole set of items with .takeWhile { ... } and will only check them one by one when .forEach { ... } is up to process the next item.
Let's try to understand this with the help of an example. First, we will work with an eager evaluation over ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access