Stream/LazyList Basics
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: