Skip to content

Instantly share code, notes, and snippets.

@Luegg
Last active August 26, 2019 12:45
Show Gist options
  • Save Luegg/7449370 to your computer and use it in GitHub Desktop.
Save Luegg/7449370 to your computer and use it in GitHub Desktop.

Desugar Scala Expressions

Use the compiler

scala -Xprint:typer -e "class A(val i: Int)" prints the desugarred expression after the typer phase. Use scala -Xshow-phases to get a list of all phases.

Or use a macro in the REPL

Paste this into a REPL session or in a file loaded with the :load command:

import scala.reflect.macros.Context
import scala.reflect.runtime.universe._
import scala.language.experimental.macros

def desugarImpl(c : Context)(expr : c.Expr[Any]): c.Expr[Unit] = {
  import c.universe._
  println(show(expr.tree))
  reify {}
}

def desugar(expr : Any) = macro desugarImpl

Use this little piece of awesomnes:

scala> desugar{
     | class A(i: Int)
     | }
{
  class A extends scala.AnyRef {
    <paramaccessor> private[this] val i: Int = _;
    def <init>(i: Int): A = {
      A.super.<init>();
      ()
    }
  };
  ()
}

Credits go to http://stackoverflow.com/questions/9891407/getting-the-desugared-part-of-a-scala-for-comprehension-expression

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment