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()
翻譯自: https://www.includehelp.com/scala/streams.aspx