I want to be able to evaluate the expression that returns from func.
The problem is that the expression includes the variable a, which is not familiar in the scope of func but is familiar in the scope of playground.
I want to be able to send the String: s"$a + 1" when $ is not an operator and s is a part of the String. I saw that $$ should solve the problem with the $, but then the char s is not a part of the String, and the eval function needs an expression with the pattern of s"".
object playground extends App{
val a = 5.5
val expression = func()
val str: String = expression
val tb = currentMirror.mkToolBox()
val x = tb.eval(tb.parse(str)).toString
print(x)
}
object second {
def func(): String = {
s"$a + 1"
}
}
Thanks for any help :)
Try to fully qualify the variable
or use import
or add a parameter to the function
I'm not sure what you're after. Try to provide some inputs and desired outputs to make it clear.
"$a + 1"is just a String (with a dollar sign),s"$a + 1"is a String where a variableafrom current scope is substituted (after.toString).Yes, you can escape
$insides"..."as$$. Sos"$$a + 1"is the same as just"$a + 1"(without prefixs).I don't understand what "
sis a part of the String", "but then the charsis not a part of the String" mean.Why?
tb.parse(orq"...") accepts arbitrary String.tb.evalaccepts arbitrary Tree.I guess I got it. It seems you are expecting
func()to expand intos"$a + 1"at a call site. Thens"$a + 1"should be not a String but a Tree itself (s"$a + 1"should be not a Strings""" s"$$a + 1" """but a piece of code) andfunc()should be a macro.But using macros (and mixing them with runtime compilation via Toolbox) in your case seems an overkill, you should prefer easier options from the above.