10.24. Creating a Lazy View on a Collection

Problem

You’re working with a large collection and want to create a “lazy” version of it so it will only compute and return results as they are actually needed.

Solution

Except for the Stream class, whenever you create an instance of a Scala collection class, you’re creating a strict version of the collection. This means that if you create a collection that contains one million elements, memory is allocated for all of those elements immediately. This is the way things normally work in a language like Java.

In Scala you can optionally create a view on a collection. A view makes the result nonstrict, or lazy. This changes the resulting collection, so when it’s used with a transformer method, the elements will only be calculated as they are accessed, and not “eagerly,” as they normally would be. (A transformer method is a method that transforms an input collection into a new output collection, as described in the Discussion.)

You can see the effect of creating a view on a collection by creating one Range without a view, and a second one with a view:

scala> 1 to 100
res0: scala.collection.immutable.Range.Inclusive =
    Range(1, 2, 3, 4, ... 98, 99, 100)

scala> (1 to 100).view
res0: java.lang.Object with 
  scala.collection.SeqView[Int,scala.collection.immutable.IndexedSeq[Int]] =
  SeqView(...)

Creating the Range without a view shows what you expect, a Range with 100 elements. However, the Range with the view shows different output in the REPL, showing something ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.