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:
Syntax
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
object Main extends App {
def naturalsFrom(n: Int): LazyList[Int] = n #:: naturalsFrom(n + 1)
val naturals = naturalsFrom(1)
println(naturals.take(5).toList)
}
Login to try C/C++/Java/PHP code in the editor
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
- Calling
.toListor.sizeon an infiniteLazyList, which never finishes; usetake(n)first. - Using
Streamin new code, when it is deprecated in Scala 2.13 in favour ofLazyList. - Assuming all elements are computed at once, when
LazyListcomputes each element only when needed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: