Skip to content

Commit

Permalink
add de-sugaring example for chapter 21
Browse files Browse the repository at this point in the history
  • Loading branch information
tobyweston committed Sep 17, 2017
1 parent 3ebcf96 commit fc717b7
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/main/scala/s4j/scala/chapter21/Desugared.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package s4j.scala.chapter21

object Desugared {

for (i <- 0 to 5) {
println(i)
}

// is de-sugared as
(0 to 5).foreach(println)


// nested loop
for (i <- 0 to 5; j <- 0 to 5) {
println(i + " " + j)
}

// is de-sugared as
(0 to 5).foreach { i =>
(0 to 5).foreach { j =>
println(i + " " + j)
}
}


// for with yield
for (i <- 0 to 5) yield {
i + 2
}

// is de-sugared as
(0 to 5).map(i => i + 2)


// more interesting example
val x: Seq[(Int, Int)] = for {
i <- 0 to 5
j <- 0 to 5
} yield {
(i, j)
}

val x2: Seq[(Int, Int)] = (0 to 5).flatMap {
i => (0 to 5).map {
j => (i, j)
}
}

}

0 comments on commit fc717b7

Please sign in to comment.