Skip to content

Commit fc717b7

Browse files
committed
add de-sugaring example for chapter 21
1 parent 3ebcf96 commit fc717b7

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
 (0)