Iterable

inline fun <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T>(source)

Given an iterator function constructs an Iterable instance that returns values through the Iterator provided by that function.

Since Kotlin

1.1

Samples


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
}
inline fun <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T>(source)

Given an iterator function constructs an Iterable instance that returns values through the Iterator provided by that function.

Since Kotlin

1.0

Samples


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
}