Internal implementation of List operations

Hi,

I am wondering how are e.g. map operations implemented. For ex:

myList.map(…).filter(…).map(…).mapNonNull(…)

Does each operation create a new List internally, or is there a kind of “predicate push” to allows kotlin to mix the operation?

In an optimization point of view, should we 1/ always try limit the list operations by using kotlin native ones (mapNonNull being better than a map then a filter) 2/ in some cases use some optimized operations (is there an explanation somewhere?) 3/ not ask the question, kotlin implementation is always the best whatever I write, and their creators are gods.

The operations on collections are evaluated eagerly and create intermediate results.
For lazily evaluated operations you should use Sequence, e.g. in your example:
myList.asSequence().map(…).filter(…).map(…).mapNonNull(…)

It is nicely described in documentation:

4 Likes