0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Taking and Filtering Lazily

Slice infinite streams.

Consuming Lazily

The real value of a LazyList shows when you consume it. Operations like take, filter, and map stay lazy, computing only the cells you ultimately force.

This lesson covers the key transformers and how to stop laziness at the right moment.

take(n)

take(n) returns a LazyList of at most the first n elements, itself still lazy. Nothing is computed until you force the result.

It is the safe way to bound an infinite stream.

object Demo extends App {
  val first5 = LazyList.from(1).take(5)
  println(first5.toList)
}

All lessons in this course

  1. Laziness Explained
  2. Building a LazyList
  3. Infinite Streams
  4. Taking and Filtering Lazily
← Back to Scala for Backend Engineering & Functional Programming