You can mix quasiquotes and ToolBox.parse
to achieve results mostly like what you are looking for:
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
Making use of your values as variables:
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)
If you evaluate q"return ${toolbox.parse(m)}"
you will see the error because x
and y
are not in scope.
scala> toolbox.eval(q"return ${toolbox.parse(m)}")
scala.tools.reflect.ToolBoxError: reflective compilation has failed:
object > is not a member of package x ...
To fix that:
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