Streams are collections
Scala collections shine as we almost never need to explicitly loop over them. Using functional combinators like map, flatMap, and filter we get things done declaratively. This comes very handy, as we will soon see.
Streams are lazy lists. You guessed right—these are collections all right:
scala> def succ(n: Int):Stream[Int] = n #:: succ(n+1) succ: (n: Int)Stream[Int] scala> lazy val r = succ(0) r: Stream[Int] = <lazy> scala> println(r.take(10).mkString(" + ")) 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 scala> val evenNums = r filter { x => x %2 == 0 } // 1 evenNums: scala.collection.immutable.Stream[Int] = Stream(0, ?)
We are jumping the gun a bit here. We are using filter, a functional combinator. We will be taking a detailed look at combinators in a next chapter. Refer to the following information box for a quick introduction.
Note
scala> val p = List(1,2,3,4) p: List[Int] = List(1, 2, 3, 4) scala> p filter { x => x > 2 } res40...