🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Views

A view is a lazy form of a collection that waits before it does any work. It runs a step only when a strict operation asks for a result.

A view runs nothing until it is forced

The counter stays at zero while the view is only built. Forcing the view is what makes the map step run.

@main def main(): Unit =
  var count = 0
  val doubled = List(1, 2, 3).view.map(x => { count += 1; x * 2 })
  println(count)
  println(doubled.toList)
  println(count)

Take forces only the items it needs

Taking two items from a view of five forces only two map steps. The other three items never run.

@main def main(): Unit =
  var seen = 0
  val nums = List(1, 2, 3, 4, 5).view.map(x => { seen += 1; x * 10 })
  val first = nums.take(2).toList
  println(first)
  println(seen)

A chained view stays lazy end to end

Filter and map on a view do nothing until toList forces the chain. The forced result is an ordinary list.

@main def main(): Unit =
  val result = List(1, 2, 3, 4, 5, 6).view.filter(_ % 2 == 0).map(_ * 10).take(2).toList
  println(result)

Example

@main def main(): Unit =
  var steps = 0
  val top = List(3, 6, 8, 9, 12).view.map(x => { steps += 1; x * 2 }).filter(_ > 10).take(2).toList
  println(top)
  println(steps)

Key points

  • Lazy: a view does no work when it is built.
  • Forcing: toList and foreach force a view to run its steps.
  • Take: take on a view limits how many items are forced.
  • Chaining: map and filter on a view stay lazy until forcing.
  • Counter: a counter inside a step shows exactly how many items ran.

In this example, the view maps each number to its double and keeps only values above 10. Forcing take(2) stops as soon as two values pass, so the map step runs three times: 3 becomes 6 and fails the filter, 6 becomes 12 and passes, and 8 becomes 16 and passes. The printed list and the step count prove the laziness.

Note

building a view costs almost nothing, because the work is deferred until forcing.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

A view maps over five items, and then take(2) is forced with toList. How many times does the map step run?