0 votes
in Scala Constructs by
Explain the term stream in Scala.

1 Answer

0 votes
by

Streams, a Scala feature, are essentially lazy lists in which elements are only evaluated as needed. In this way, Scala allows for faster processing. Streams are similar to lists in terms of performance.

Syntax: 

 val str = 1 #:: 2 #:: 3 #:: Stream.empty

Scala lets you construct Lists by using the :: operator, while you can build Streams by using the #:: operator with Stream.empty at the end of the expression. A stream's head in the above syntax is 1, while its tail is 2 and 3. 

Example:  

 object MainObject 

{   

    def main(args:Array[String]){   

        val stream = 20 #:: 30 #:: 45 #:: Stream.empty   

        println(stream)   

    }   

}   

Output: 

Stream(20, ?) 

Observe the output and you will see a question mark instead of the second element. Scala only evaluates lists if they are needed. 

...