Sequence

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

Given an iterator function constructs a Sequence that returns values through the Iterator provided by that function. The values are evaluated lazily, and the sequence is potentially infinite.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val array = arrayOf(1, 2, 3)

// create a sequence with a function, returning an iterator
val sequence1 = Sequence { array.iterator() }
println(sequence1.joinToString()) // 1, 2, 3
println(sequence1.drop(1).joinToString()) // 2, 3

// create a sequence from an existing iterator
// can be iterated only once
val sequence2 = array.iterator().asSequence()
println(sequence2.joinToString()) // 1, 2, 3
// sequence2.drop(1).joinToString() // <- iterating sequence second time will fail 
   //sampleEnd
}