Getting the desugared part of a Scala for/comprehension expression?

As I already said in the other topic, scalac -print prints out scala code, not java. It translates all scala keywords that are not directly compatible with java to normal scala code. It is not possible to let the compiler translate only parts afaik. But basically a for-comprehension is always translated the same way.

A simple for/yield like this

for(x <- List(1,2,3)) yield x*x

will be translated to

List(1,2,3).map {x => x*x}

And without yield

for(x <- List(1,2,3)) println(x)

to

List(1,2,3).foreach{x => println(x)}

Nested fors will be translated to nested flatMap/map constructs

for(x <- List(1,2,3); y <- List(4,5,6)) yield x*y

will be translated to

List(1,2,3).flatMap { x =>
  List(4,5,6).map { y =>
    x*y
  }
}

So there is absolutely no magic

Leave a Comment