Home »
Scala
Streams in Scala
By IncludeHelp Last updated : November 14, 2024
Scala Streams
Stream in Scala is a type of lazy val. It is a lazy val whose elements are evaluated only when they are used in the program. Lazy initialization is a feature of Scala that increases the performance of the program.
Syntax
val str = 1 #:: 2 #:: 3 #:: Stream.empty
Elements of a stream are created using #:: operator using Stream.empty at the end of initialization.
Program to show the creation of a stream
object myObject
{
def main(args: Array[String]): Unit = {
val myStream = 2 #:: 4 #:: 6 #:: Stream.empty;
println("New Stream created...")
println(myStream)
}
}
Output
New Stream created...
Stream(2, <not computed>)
Creating stream using stream.cons
You can create a stream using stream.cons. It will create an immutable stream and needs an import statement Scala.collection.immutable.Stream.cons.
import scala.collection.immutable.Stream.cons
object myObject
{
def main(args: Array[String]): Unit = {
val myStream: Stream[Int] = cons(2, cons(4, cons(6, Stream.empty)))
println("New Stream created...")
println(myStream)
}
}
Output
New Stream created...
Stream(2, <not computed>)
Accessing elements of the stream
In streams, take method is used to take/access elements.
Program to access elements using take method
import scala.collection.immutable.LazyList.cons
object myObject {
def main(args: Array[String]): Unit = {
val myStream: LazyList[Int] = cons(2, cons(4, cons(6, cons(9, LazyList.empty))))
print("Accessing Stream: ")
println(myStream)
print("\nTake first 2 elements of stream: ")
myStream.take(2).foreach(print)
print("\n\nTake all elements from stream: ")
myStream.take(5).foreach(print)
}
}
Output
Accessing Stream : Stream(2, <not computed>)
Take first 2 elements of stream : 2, 4
Take all elements from stream : 2, 4, 6, 9
Creating an empty Stream
You can create an empty stream in Scala using Stream.empty.
object myObject
{
def main(args: Array[String]): Unit = {
val myStream: Stream[Int] = Stream.empty[Int]
print("This is an empty Stream : ")
println(myStream)
}
}
Output
This is an empty Stream : Stream()