TExcelTAD
Home › Scala › Scala Lazy Collections

Scala Lazy Collections

Normal (strict) collections compute every element immediately. Lazy collections compute elements only when they are actually needed. That lets you describe huge or even infinite sequences and avoid building big intermediate collections. Scala offers three tools: LazyList, views and Iterator.

Strict vs. lazy

Here a chain of map and filter on a List does all the work for every element, even though we only want the first two results:

scala · try it yourself
@main def run(): Unit =
  val strict = List(1, 2, 3, 4, 5)
    .map { n => println(s"map $n"); n * 10 }
    .filter(_ > 15)
    .take(2)
  println(strict)
map 1
map 2
map 3
map 4
map 5
List(20, 30)

With a view, nothing happens until the result is forced, and only as much work is done as needed:

scala · try it yourself
@main def run(): Unit =
  val lazyResult = List(1, 2, 3, 4, 5).view
    .map { n => println(s"map $n"); n * 10 }
    .filter(_ > 15)
    .take(2)
  println("nothing computed yet")
  println(lazyResult.toList)
nothing computed yet
map 1
map 2
map 3
List(20, 30)

Elements 4 and 5 were never touched.

Views

Call .view on any collection to get a lazy wrapper. Transformations on the view are recorded, not run. Call toList, toVector, sum or similar to compute the final result.

Step Strict collection View
map, filter build a new collection each time record the operation
take(n) copies the first n limits further work
toList / sum — runs the whole pipeline once, element by element

Note: A view re-runs its pipeline every time you force it. If you need the result more than once, convert it to a strict collection once and keep that.

LazyList: possibly infinite sequences

A LazyList computes its elements on demand and remembers them (memoisation). Because elements are only computed when needed, it can be infinite.

scala · try it yourself
@main def run(): Unit =
  val naturals = LazyList.from(1)
  println(naturals.take(5).toList)

  val powersOfTwo = LazyList.iterate(1)(_ * 2)
  println(powersOfTwo.take(10).toList)

  val firstBigSquare = naturals.map(n => n * n).find(_ > 500)
  println(firstBigSquare)
List(1, 2, 3, 4, 5)
List(1, 2, 4, 8, 16, 32, 64, 128, 256, 512)
Some(529)

Defining a LazyList recursively

The #:: operator builds a lazy list whose tail is evaluated only when needed. This makes classic infinite sequences a one-liner.

scala · try it yourself
@main def run(): Unit =
  lazy val fibs: LazyList[BigInt] =
    BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map(_ + _)
  println(fibs.take(12).toList)
  println(fibs(80))

  def primes(candidates: LazyList[Int]): LazyList[Int] =
    candidates.head #:: primes(candidates.tail.filter(_ % candidates.head != 0))
  println(primes(LazyList.from(2)).take(10).toList)
List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
23416728348467685
List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)

Tip: Never call .toList, .size or .sum on an infinite LazyList without take or takeWhile first — it would run forever (or until memory runs out).

Iterator: lazy and single-use

An Iterator produces elements one at a time and can be traversed only once. Reading files line by line with scala.io.Source gives you an iterator, for example.

scala · try it yourself
@main def run(): Unit =
  val it = Iterator(3, 6, 9, 12)
  println(it.next())
  println(it.filter(_ > 5).map(_ / 3).toList)
  println(it.hasNext)

  val countdown = Iterator.iterate(5)(_ - 1).takeWhile(_ > 0)
  println(countdown.mkString(" "))
3
List(2, 3, 4)
false
5 4 3 2 1

After the second line the iterator is exhausted, so hasNext is false.

Which one should I use?

Tool Memoises? Reusable? Typical use
view no yes (re-computes) avoid intermediate collections in long chains
LazyList yes yes infinite or expensive sequences you read more than once
Iterator no no (single pass) streaming data such as file lines

Test yourself

What does calling .view on a List do?

  1. Prints the list
  2. Returns a lazy wrapper; transformations run only when forced
  3. Makes the list mutable
  4. Sorts the list

Why can LazyList.from(1) exist even though it is infinite?

  1. It stores all numbers compressed
  2. Elements are computed only when requested
  3. It stops at Int.MaxValue immediately
  4. It is actually a Range

What is special about an Iterator?

  1. It can be traversed only once
  2. It is always sorted
  3. It is immutable and reusable
  4. It cannot be filtered