# Lazy List, a Scala language concept

Last updated

The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').

### Key example

This example shows how a LazyList is evaluated.

``````var itemsEvaluated = 0

def nextNumber(i: Int): Int = {
itemsEvaluated += 1
i + 1
}

val numbersFrom1: LazyList[Int] =
LazyList.iterate(nextNumber(0))(i => nextNumber(i))

assert(itemsEvaluated == 0)

assert(itemsEvaluated == 1)

assert(numbersFrom1.take(5).length == 5)

assert(itemsEvaluated == 5)

assert(numbersFrom1.take(5).toList == List(1, 2, 3, 4, 5))
``````

In particular, notice that the values that were pulled out are persisted for futher retrieval.

### Self-recursion

Perhaps most interesting is the canonical example of how to use LazyList, where it refers to itself: the Fibonacci sequence. Have a look at the solution here: FibonacciLazyList.

### Memory safety

LazyList may persist the items in memory for longer than needed, so do be careful about them, and test their edge cases when you work with them.

In practice, use cases of LazyList are few, and it may make more sense to use things like View, which provides lazy non-persistent evaluation. Ultimately, it will depend on your use case.

# Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

## How our 100 algorithms look

1. A description/goal of the algorithm.
2. An explanation with both Scala and logical parts.
3. A proof or a derivation, where appropriate.
4. Links to Scala concepts used in this specific algorithm, also unit-tested.
5. An implementation in pure-functional immutable Scala, with efficiency in mind (for most algorithms, this is for paid subscribers only).
6. Unit tests, with a button to run them immediately in our in-browser IDE.

### Study our 100 Scala Algorithms: 6 fully free, 100 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

### Explore the 22 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

## Subscribe to Scala Algorithms

Maximize your Scala with disciplined and consistently unit-tested solutions to 100+ algorithms.

Use it from improving your day-to-day data structures and Scala; all the way to interviewing.