Does anyone know how to get the (Scala part only) desugared translation of a for/comprehension expression before it actually tries to compile in the REPL (or compiler)?
The only thing I've found so far is the compiler "-print" flag but that gives you the full Scala translation…
It doesn't seem to exists any possibilities to desugar "for/comprehension" expressions directly within the REPL. But as an alternative one can use some Scala compiler options like "-print" or for simple expressions "Xprint:typer -e"
Example:
To get the desugard output from a file use the "-print" flag:
To desugar a simple one-liner expression, use the "-Xprint:typer -e" flag:
Intellij has a feature called "Explain Scala" that does a LOT of desugaring including expanding for comprehensions into map/flatMap/filter directly in the file you are editing.
Please note that since IntelliJ 2017.1 this is now called "Desugar Scala Code" and is in the "Code" menu (thanks Mikaël for the info).
How about a macro?
This can be used directly in the REPL, as per your request:
It also works on other arbitrary expressions.
This is probably the closest you'll get to what you're asking without ever having to compile or dump the data out to a file at any point. You can define the macro directly in the REPL, or in an external file loaded with the
:load
command.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
will be translated to
And without yield
to
Nested fors will be translated to nested flatMap/map constructs
will be translated to
So there is absolutely no magic
In scala 2.11, it is also possible to use quasiquotes:
To see the result after simple desugaring use the
-Xprint:parser
option.If you have this simple input file named
test.scala
:Then compiling it using
scalac -Xprint:parser
prints out:To get a complete list of compiler phases applicable to
-Xprint:<phase>
do this:The
-Xprint:<phase>
option is also applicable toscala
and thus to the REPL. However, you will see all the wrapper code the REPL inserts as well.