从Scala中经过类型化检查的`Tree`中提取类型

时间:2015-07-07 13:52:01

标签: scala types

给出以下REPL会话:

tee

从类型检查树scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> import scala.tools.reflect.ToolBox import scala.tools.reflect.ToolBox scala> import scala.reflect.runtime.{currentMirror => cm} import scala.reflect.runtime.{currentMirror=>cm} scala> val r = reify { val a = 234.45 } r: reflect.runtime.universe.Expr[Unit] = Expr[Unit]({ val a = 234.45; () }) scala> val c = cm.mkToolBox().typecheck(r.tree) warning: there was one feature warning; re-run with -feature for details c: qual$2.u.Tree forSome { val qual$2: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] @scala.reflect.internal.annotations.uncheckedBounds } = { val a: Double = 234.45; () } 中提取变量类型a的推荐方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用quasiquotes来完成,但我不确定这是最简单的方法:

scala> val c = cm.mkToolBox().typecheck(r.tree)
warning: there was one feature warning; re-run with -feature for details
c: qual$2.u.Tree forSome { val qual$2:     scala.tools.reflect.ToolBox[reflect.runtime.universe.type]     @scala.reflect.internal.annotations.uncheckedBounds } =
{
  val a: Double = 234.45;
  ()
}

scala> val q"{val $name: $tpt = $rhs; ()}" = c
name: reflect.runtime.universe.TermName = a
tpt: reflect.runtime.universe.Tree = Double
rhs: reflect.runtime.universe.Tree = 234.45

scala> :t tpt.tpe
reflect.runtime.universe.Type

scala> println(tpt.tpe)
Double