0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Infinite Streams

Model endless data safely.

Infinity, Safely

A LazyList can describe an infinite sequence because its tail is never computed until demanded. You only ever materialize the prefix you consume.

This lets you model natural numbers, primes, or sensor readings without bounding them up front.

All Natural Numbers

LazyList.from(1) is the infinite sequence 1, 2, 3, ... You can take any finite prefix.

Forcing the whole thing would never finish, so always slice it with take or stop with a predicate.

object Demo extends App {
  val nats = LazyList.from(1)
  println(nats.take(5).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