Since streams were introduced only in Java 8, but Kotlin is backward-compatible down to Java 6, it needed to provide another solution for the possibility of infinite collections. This solution was named sequenced, so it won't clash with Java streams when they're available.
You can generate an infinite sequence of numbers, starting with 1:
val seq = generateSequence(1) { it + 1 }
To take only the first 100, we use the take() function:
seq.take(100).forEach {
println(it)
}
A finite number of sequences can be created by returning null:
val finiteSequence = generateSequence(1) {
if (it < 1000) it + 1 else null
}
finiteSequence.forEach {
println(it)
} // Prints numbers up to 1000
A finite number of sequences can be created from ranges or collections by calling asSequence():
(1..1000).asSequence()