iterator

fun <T> iterator(block: suspend SequenceScope<T>.() -> Unit): Iterator<T>(source)

Builds an Iterator lazily yielding values one by one.

If the consuming code stops using the iterator without Iterator.hasNext returning false first, the remainder of the computation will not run at all. In particular, it means that finally blocks may be left unexecuted:

val singleElementIterator = iterator {
try {
yield(1)
// no code after the `yield(1)` line will be executed!
} finally {
println("This line will not run")
}
}
// only get the first element, do not attempt evaluating the rest of them
if (singleElementIterator.hasNext()) {
println(singleElementIterator.next())
}

Since Kotlin

1.3

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val collection = listOf(1, 2, 3)
val wrappedCollection = object : AbstractCollection<Any>() {
    override val size: Int = collection.size + 2

    override fun iterator(): Iterator<Any> = iterator {
        yield("first")
        yieldAll(collection)
        yield("last")
    }
}

println(wrappedCollection) // [first, 1, 2, 3, last] 
   //sampleEnd
}

fun main() { 
   //sampleStart 
   val iterable = Iterable {
    iterator {
        yield(42)
        yieldAll(1..5 step 2)
    }
}
val result = iterable.mapIndexed { index, value -> "$index: $value" }
println(result) // [0: 42, 1: 1, 2: 3, 3: 5]

// can be iterated many times
repeat(2) {
    val sum = iterable.sum()
    println(sum) // 51
} 
   //sampleEnd
}