scala quasiquotes字符串变量提升多个步骤

时间:2017-09-13 15:09:30

标签: scala scala-quasiquotes lifting

这就是我想要的:

scala> var x:Int = 10
x: Int = 10

scala> var y:Int = 20
y: Int = 20

scala> val ret = q"return $x>$y"
ret: universe.Return = return 10.$greater(20)

scala> val result1 = toolbox.compile(ret)()
result1: Any = false

但问题是我将在字符串var中得到表达式$ x> $ y,例如

scala> m
res20: String = $x>$y

然后我想执行操作,

var ret = q"return $m"

但这回归:

scala> var ret = q"return $m"
ret: universe.Return = return "$x>$y"

不符合此目的。如何在最后一步获得x和y的值,而不是 $ x和$ y。

1 个答案:

答案 0 :(得分:0)

你可以混合使用quasiquotes和ToolBox.parse来达到你想要的结果:

import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._

val toolbox = scala.reflect.runtime.currentMirror.mkToolBox()

val s = "10>20"
val ret = q"return ${toolbox.parse(s)}"
// reflect.runtime.universe.Return = return 10.$greater(20)
toolbox.eval(ret)
// Any = false

将您的值用作变量:

import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._
val toolbox = scala.reflect.runtime.currentMirror.mkToolBox()
val x = 10
val y = 20
val m = "x>y"
val ret = q"return ${toolbox.parse(m)}"
// reflect.runtime.universe.Return = return x.$greater(y)

如果您评估q"return ${toolbox.parse(m)}",则会看到错误,因为xy不在范围内。

scala> toolbox.eval(q"return ${toolbox.parse(m)}")
scala.tools.reflect.ToolBoxError: reflective compilation has failed:

object > is not a member of package x ...

解决这个问题:

import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._
val toolbox = scala.reflect.runtime.currentMirror.mkToolBox()
val q1 = q"val x = 10; val y = 20; "
val m = "x>y"
val ret = q"""
     |   ..$q1
     |   return ${toolbox.parse(m)}
     | """
toolbox.eval(ret)
// Any = false