Quick Tip : Streams in Scala

There are cases where one has to use the first n numbers of an infinite sequence
of numbers (like the Fibonacci numbers for example) but, unfortunately, there is
no way to determine how many members of the sequence will be actually needed.

Scala offers an better solution for the same – the ability to define infinite sized data structures whose elements are computed on demand.These data structures are called streams. A stream is a list whose elements are not computed eagerly, but rather lazily. Eager evaluation means that a function first evaluates its arguments and then it uses them, while lazy evaluation means that an argument is evaluated only when it is needed.

Streams are created using the constant empty and the constructor cons, which are
both deﬁned in module scala.Stream. For example, the following expression constructs a stream with elements 1 and 2:

Stream.cons(1, Stream.cons(2, Stream.empty))

Let us take an simple example :

This code can be used to create such a stream:

def numsFrom (n :Int):Stream[Int] = Stream.cons(n,numsFrom (n+1))

Now we can create an “infinite” stream using the following command:

lazy val N = numsFrom(0)

The keyword lazy designates that the value assigned to the constant N should not
be evaluated. Now for the following expression

N take 10 print

Your output would be :

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

Let us take another simple example. Suppose we want to print the number “10” for desired times then using stream this can be written as :