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

Stream/LazyList Basics

A LazyList produces its items only when asked, like a story that writes the next page when you turn to it. It can even describe an endless list without making it all at once.

In this page:

  1. Stream/LazyList Basics
Syntax
scala
val lazyList = LazyList.from(start)
val firstItems = lazyList.take(n).toList
val infinite = LazyList.iterate(seed)(x => next_expression)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling .toList or .size on an infinite LazyList, which never finishes; use take(n) first.
  2. Using Stream in new code, when it is deprecated in Scala 2.13 in favour of LazyList.
  3. Assuming all elements are computed at once, when LazyList computes each element only when needed.
🔒

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.