← All languages
Kotlin function of the day
Random

generateSequence

Generate a sequence from a seed and a next-value function.

Description

The generateSequence function creates a sequence that produces values by repeatedly applying the nextFunction, starting with the given seed value. The sequence terminates when nextFunction returns null.

There is also a seedless overload where the first call to nextFunction produces the initial element. The sequence is lazy, computing values only when requested.

generateSequence is useful for iterating linked structures, computing mathematical series, or any scenario where each value depends on the previous one.

Arguments

NameDescriptionOptional
seed The initial value of the sequence. Yes
nextFunction A function that takes the previous value and returns the next, or null to terminate. No

Example

val powers = generateSequence(1) { it * 2 }
println(powers.take(8).toList())  // [1, 2, 4, 8, 16, 32, 64, 128]

Reference