August 2018
Intermediate to advanced
380 pages
10h 2m
English
The for statement is a little bit more unconventional. In fact, the for statement is syntactic sugar for an application of the foreach, map, and flatMap methods. For example, take a look at the following expression:
scala> val list = 0 to 3list: scala.collection.immutable.Range.Inclusive = Range 0 to 3scala> val result = | for { | e <- list | list2 = 0 to e | e2 <- list2 | } yield (e, e2)result: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,0), (1,0), (1,1), (2,0), (2,1), (2,2), (3,0), (3,1), (3,2), (3,3))scala> println(result.mkString("\n"))(0,0)(1,0)(1,1)(2,0)(2,1)(2,2)(3,0)
(3,1)(3,2)(3,3)
The preceding for expression expands to the following method applications:
scala> val result = list.flatMap { e => | val list2 ...