← Back to Scala Course | Chapter 12: Advanced Features | Lesson 6 of 7

Stream/LazyList Basics

In this page:

  1. Stream/LazyList Basics

Stream/LazyList Basics

LazyList (the modern replacement for the deprecated Stream as of Scala 2.13) is a lazily-evaluated, potentially infinite sequence, where elements are computed only as they're accessed and then cached. This lets you define an infinite sequence, like all natural numbers, and safely take just the first few elements with .take(n). #:: is used to lazily prepend an element to a LazyList, mirroring :: for a strict List.

Warning: Calling something like .toList directly on an infinite LazyList without first calling .take(n) will never terminate.

Example: Stream/LazyList Basics

markup
object Main extends App {
  def naturalsFrom(n: Int): LazyList[Int] = n #:: naturalsFrom(n + 1)

  val naturals = naturalsFrom(1)
  println(naturals.take(5).toList)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.