0
0
Kotlinprogramming~5 mins

Generating infinite sequences in Kotlin

Choose your learning style9 modes available
Introduction

Generating infinite sequences lets you create endless lists of values without using too much memory. You can get values one by one as you need them.

When you want to create a list of numbers that never ends, like all natural numbers.
When you need to process data step-by-step without loading everything at once.
When you want to generate repeated patterns or calculations lazily.
When you want to handle streams of data that keep coming, like sensor readings.
When you want to save memory by not storing all values at once.
Syntax
Kotlin
val sequence = generateSequence(seed) { nextValue -> nextValue + 1 }

seed is the first value of the sequence.

The lambda after seed defines how to get the next value from the current one.

Examples
This creates an infinite sequence of numbers starting from 1, increasing by 1 each time.
Kotlin
val numbers = generateSequence(1) { it + 1 }
This creates an infinite sequence of even numbers starting from 0.
Kotlin
val evenNumbers = generateSequence(0) { it + 2 }
This creates an infinite Fibonacci sequence by generating pairs and mapping to the first number.
Kotlin
val fibonacci = generateSequence(Pair(0, 1)) { Pair(it.second, it.first + it.second) }.map { it.first }
Sample Program

This program creates an infinite sequence of numbers starting at 1. It then takes the first five numbers and prints them as a list.

Kotlin
fun main() {
    val numbers = generateSequence(1) { it + 1 }
    val firstFive = numbers.take(5).toList()
    println("First five numbers: $firstFive")
}
OutputSuccess
Important Notes

Infinite sequences do not store all values, so they save memory.

Use functions like take() to get a limited number of items; otherwise, the program may run forever.

You can transform sequences with map, filter, and other sequence functions.

Summary

Infinite sequences generate values one by one as needed.

They start from a seed and use a function to get the next value.

Always limit infinite sequences when using them to avoid endless loops.