September 2018
Intermediate to advanced
398 pages
9h 43m
English
Here is a function definition that calls the strict methods of Vector:
def evenPlusOne(xs: Vector[Int]): Vector[Int] = xs.filter { x => println(s"filter $x"); x % 2 == 0 } .map { x => println(s"map $x"); x + 1 }evenPlusOne(Vector(0, 1, 2))
It prints the following on the console:
filter 0filter 1filter 2map 0map 2res4: Vector[Int] = Vector(1, 3)
We can see that Vector is iterated twice: once for filter, and once for map. But our evenPlusOne function would be faster if it could iterate only once. One way to do this would be to change the implementation and use collect. Another way would be to use the non-strict withFilter method, as shown in the following code:
def lazyEvenPlusOne(xs: Vector[Int]): Vector[Int] = xs.withFilter ...
Read now
Unlock full access