Search code examples
scalakotlinstreamlazy-sequencesscala-streams

Do Kotlin Sequences cache intermediate results?


When operating Kotlin sequences with functional APIs such as map, flatMap, +, etc., are computed intermediate results cached so upon second evaluation there is no recomputation?

If not, replacing Lists with Sequences could in some situations cause complexity to blow up exponentially, and the word "lazy" used in official docs seems not precise enough to distinguish the two behaviors.

In other words, comparing to Scala, are Kotlin Sequences more like Scala Streams/LazyLists (where "Once computed, a value stays computed and is reused. Or, as you say, the values are cached.") or Views (where "all transformations are re-applied each time you need to fetch elements from it")? (quoted content from What is the difference between view, stream and iterator? | FAQ | Scala Documentation)


Solution

  • The sequence is re-evaluated every time you call a terminal function on it. But you can evaluate it with toList() to complete the evaluation one time and use the list for subsequent operations.