🐦 Kotlin Intermediate

What is a Sequence in Kotlin and how does it differ from a List?

Answer

A Sequence is a lazily-evaluated collection that processes elements one at a time rather than creating intermediate collections at each step. When you chain operations on a regular List (filter then map), each operation creates a new intermediate list. With Sequences, all operations are applied to each element in one pass. Convert any collection to a sequence with asSequence(). Sequences are more efficient for large collections with multiple chained transformations, or when you only need the first few results. However, for small collections, the overhead of lazy evaluation can make Sequences slower.