Scala | 流 (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.
Scala中的Stream是一种惰性val 。 这是一个懒惰的val,其元素仅在程序中使用时才被评估。 延迟初始化是Scala的一项功能,可以提高程序的性能。
Syntax:
句法:
val str = 1 #:: 2 #:: 3 #:: Stream.empty
Elements of a stream are created using #:: operator using Stream.empty at the end of initialization.
在初始化结束时,使用#::运算符使用Stream.empty创建流的元素。
Program to show the creation of a stream
显示流创建的程序
object myObject
{
def main(args:Array[String])
{
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
使用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.
您可以使用stream.cons创建流。 它将创建一个不可变的流,并且需要一个导入语句Scala.collection.immutable.Stream.cons 。
import scala.collection.immutable.Stream.cons
object myObject
{
def main(args:Array[String])
{
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.
在流中, take方法用于获取/访问元素。
Program to access elements using take method
程序使用take方法访问元素
import scala.collection.immutable.Stream.cons
object myObject
{
def main(args:Array[String])
{
val myStream: Stream[Int] = cons(2, cons(4, cons(6, cons(9, Stream.empty))))
print("Accessing Stream : ")
print(myStream)
print("\nTake first 2 elements of stream : ")
myStream.take(2).print
print("\nTake all elements from stream : ")
myStream.take(5).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.
您可以使用Stream.empty在Scala中创建一个空流。
object myObject
{
def main(args:Array[String])
{
val myStream: Stream[Int] = Stream.empty[Int]
print("This is an empty Stream : ")
println(myStream)
}
}
Output
输出量
This is an empty Stream : Stream()