Starting with version 1.23, Go has added support for iterators, which lets us range over pretty much anything!
Let’s look at the List type from the previous example again. In that example, we had an AllElements method that returned a slice of all elements in the list. With Kotlin iterators (known as sequences), we can do it better - as shown below.
Define the List Class
We start by defining a generic List class to store elements.
Push Method
The push method adds an element to the end of the list.
All Method
The all method returns a Kotlin sequence, which is an iterator that lazily evaluates the elements in the list.
Generate Fibonacci Sequence
We define a genFib function that generates an infinite sequence of Fibonacci numbers using a Kotlin sequence.
Main Function
In the main function, we create a List, add elements to it, and then iterate over them using the all method.
This code demonstrates how to iterate over custom data structures using Kotlin sequences, providing a modern and idiomatic way to handle iteration in Kotlin.