File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
src/main/scala/s4j/scala/chapter21 Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package s4j .scala .chapter21
2
+
3
+ object Desugared {
4
+
5
+ for (i <- 0 to 5 ) {
6
+ println(i)
7
+ }
8
+
9
+ // is de-sugared as
10
+ (0 to 5 ).foreach(println)
11
+
12
+
13
+ // nested loop
14
+ for (i <- 0 to 5 ; j <- 0 to 5 ) {
15
+ println(i + " " + j)
16
+ }
17
+
18
+ // is de-sugared as
19
+ (0 to 5 ).foreach { i =>
20
+ (0 to 5 ).foreach { j =>
21
+ println(i + " " + j)
22
+ }
23
+ }
24
+
25
+
26
+ // for with yield
27
+ for (i <- 0 to 5 ) yield {
28
+ i + 2
29
+ }
30
+
31
+ // is de-sugared as
32
+ (0 to 5 ).map(i => i + 2 )
33
+
34
+
35
+ // more interesting example
36
+ val x : Seq [(Int , Int )] = for {
37
+ i <- 0 to 5
38
+ j <- 0 to 5
39
+ } yield {
40
+ (i, j)
41
+ }
42
+
43
+ val x2 : Seq [(Int , Int )] = (0 to 5 ).flatMap {
44
+ i => (0 to 5 ).map {
45
+ j => (i, j)
46
+ }
47
+ }
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments