Scala stream example

You can easily generate an infinite stream:

val x = Stream.from(1)

x: scala.collection.immutable.Stream[Int] = Stream(1, ?)

Using this, you can pull values, however the “take” results will still be a lazy-loaded stream:

x.take(10)

res11: scala.collection.immutable.Stream[Int] = Stream(1, ?)

You have to manually force this to return what you want:

x.take(10).toList
res12: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Alternately, you can use this as more complex constructions. For instance, shown here, you can find the first ten numbers divisible by five:

x.filter(_ % 5 == 0).take(10).toList

res16: List[Int] = 
  List(5, 10, 15, 20, 
       25, 30, 35, 40, 45, 50)