What are the differences between the following collections types in Scala: List and LazyList types?
Asked
Active
Viewed 3,739 times
6
Dina Bogdan
- 4,345
- 5
- 27
- 56
2 Answers
6
LazyList is a new type introduced in Scala Standard Library 2.13.1.
- The type it's an immutable one and it's placed into
scala.collection.immutablepackage. The major difference between the commonListtype is the fact that the elements of theLazyListare computed lazily, so only those elements that are requested are computed. By this means, a lazy list can have an infinite number of elements. - In terms of performance, the two types (
LazyListandList) are comparable. - A
LazyListis constructed with an operator having a similar-looking to the one specific to theListtype (::),#::. - Being lazy, a
LazyListcan't produce aStackOverFlowErrorin a recursive loop, as an oldListcould do.
Dina Bogdan
- 4,345
- 5
- 27
- 56
4
The question
What are the differences between
LazyListandList?
can be rephrased as the question
What are the differences between
StreamandList?
because by Scala 2.13 release notes
immutable.LazyListreplacesimmutable.Stream.Streamhad different laziness behavior and is now deprecated. (#7558, #7000)
and the answer to the rephrased question is provided by what is the difference between Scala Stream vs Scala List vs Scala Sequence.
Performance judgements are best addressed by measurements within particular scenarios.
Mario Galic
- 47,285
- 6
- 56
- 98