2017-09-13 2 views
0

das ist, was ich will:scala quasiquotes String-Variable Hebe in mehreren Schritten

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 

Aber das Problem ist, dass ich den Ausdruck $ x> $ y in einem String var bekommen, wie

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

Und dann will ich die Operation als auszuführen,

var ret = q"return $m" 

aber diese Rückkehr:

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

die nicht den Zweck erfüllt. Wie kann ich den Wert von x und y im letzten Schritt statt $ x und $ y erhalten.

Antwort

0

Sie können quasiquotes mischen und ToolBox.parse Ergebnisse zu erzielen meist wie das, was Sie suchen:

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 

Verwendung Ihrer Werte als Variablen zu machen:

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) 

Wenn Sie q"return ${toolbox.parse(m)}" auswerten werden Sie Siehe den Fehler, da x und y nicht im Geltungsbereich sind.

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

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

das beheben:

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 
+0

Danke für die Antwort. Ich habe noch eine Frage hier. Die Linie: – Pankaj

Verwandte Themen