O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required