Sequences
Functional programming languages have long featured higher-order functions for collections. However, for Java developers, this concept became significant with the introduction of the Stream API in Java 8.
The Stream API offers useful functions like map()
, filter()
, and others, but requires converting your collection into a stream to use these operations. To obtain your collection again, you would have to collect the stream again. This can lead to an OutOfMemoryError
if the stream is infinite, though.
In Kotlin, sequences serve a similar purpose to Java streams. Kotlin’s alternative is called a sequence just to avoid naming conflicts with Java streams, for projects that mix Java and Kotlin code together, or that depend on Java libraries. Unlike Java streams, which are specific to the JVM ecosystem, Kotlin sequences are not restricted to the JVM.
Sequences offer a blocking API to a potentially infinite stream of data.
Creating a new sequence in Kotlin...