July 2018
Intermediate to advanced
266 pages
7h 11m
English
Another useful function is hasNext(), which returns true if the iterator can emit one more element, and false otherwise. An example of this could be the following:
fun main(args: Array<String>) { val iterator = buildIterator { for (i in 0..4) { yield(i * 4) } } for (i in 0..5) { if (iterator.hasNext()) { println("element $i is ${iterator.next()}") } else { println("No more elements") } }}
In this example, we create an iterator that yields a number the first five times it's invoked. Then we call it six times. The result is as expected:

Read now
Unlock full access