In Kotlin, how does a Sequence
differ from an Iterable
Collection?
Can you think of any scenarios where a Sequence
would perform better than an Iterable
?
A Sequence
is a different container type in Kotlin. It has the same functions as Iterable
s (like List
) but handles these functions in a “multi step” way.
- Basically an Iterable will do each chained function like filter, map, etc on the entire Iterable before moving to the next function in the chain.
- A Sequence will do each function in the chain on each element of the Sequence before moving on to the next element.
When to use a Sequence
:
- Many or expensive operations to perform on a collection.
- When processing can short circuit. (end early because a result is found)
- The operation is stateless.
- The collection is smaller.
When to use Iterable
- When collecting the results (
toList()
, toSet()
)
- The operation is stateful.
- The collection is larger.
Stateful - other collections are needed to perform the operation
Stateless - no other collections needed to perform an operation