What's the easiest way to use reify (get an AST of) an expression in Scala?

前端 未结 2 854
半阙折子戏
半阙折子戏 2020-11-29 17:58

I\'m looking at alternatives to -print or javap as a way of figuring out what the compiler is doing in Scala. With the new reflection/macros librar

2条回答
  •  -上瘾入骨i
    2020-11-29 18:10

    There is improve of new Scala version

    scala> import scala.tools.reflect.ToolBox
    import scala.tools.reflect.ToolBox
    
    scala> import scala.reflect.runtime.{currentMirror => m}
    import scala.reflect.runtime.{currentMirror=>m}
    
    scala> val tb = m.mkToolBox()
    tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@78dc5f15
    
    scala> val tree = tb.parseExpr("1 to 3 map (_+1)")
    :10: error: value parseExpr is not a member of scala.tools.reflect.ToolBox[reflect.runtime.universe.type]
           val tree = tb.parseExpr("1 to 3 map (_+1)")
                         ^
    
    scala> val tree = tb.parse("1 to 3 map (_+1)")
    tree: tb.u.Tree = 1.to(3).map(((x$1) => x$1.$plus(1)))
    
    scala> val eval = tb.eval(tree)
    eval: Any = Vector(2, 3, 4)
    

提交回复
热议问题