scala學習筆記:理解stream和view

白喬發表於2015-03-01

先來個正常的:

scala> (0 to 5).map((x:Int)=>{println(x);x*2}).foreach(println)
0
1
2
3
4
5
0
2
4
6
8
10

再來個stream版的:

scala> (0 to 5).toStream.map((x:Int)=>{println(x);x*2}).foreach(println)
0
0
1
2
2
4
3
6
4
8
5
10

最後來個view版的:

scala> (0 to 5).view.map((x:Int)=>{println(x);x*2}).foreach(println)
0
0
1
2
2
4
3
6
4
8
5
10

目前看,view和stream的表現一樣,那麼區別何在呢?觀察下一個:

scala> (0 to 5).toStream.map((x:Int)=>{println(x);x*2})
0
res5: scala.collection.immutable.Stream[Int] = Stream(0, ?)

scala> (0 to 5).view.map((x:Int)=>{println(x);x*2})
res6: scala.collection.SeqView[Int,Seq[_]] = SeqViewM(...)

看來stream會優先求第一個值的!這就是區別的全部麼?

相關文章