February 2018
Intermediate to advanced
552 pages
13h 46m
English
Scala supports a very rich For loop construct known as For-comprehension. We can use it like Java's extended For loop, as shown here:
scala> val numList = List(1,2,3,4,5) numList: List[Int] = List(1, 2, 3, 4, 5) scala> for(num <- numList) yield num+1 res7: List[Int] = List(2, 3, 4, 5, 6)
When we observe the preceding example, we realize that For-comprehension results in the same container or object with a new set of elements.
We can use For-comprehension to replace the operation that uses both filter and map, as shown here:
scala> val numList = List(1,2,3,4,5) numList: List[Int] = List(1, 2, 3, 4, 5) scala> numList.filter(a => a %2 == 0).map(b => b*b) res8: List[Int] = List(4, 16) scala> ...
Read now
Unlock full access