您能否解释一下为什么下面 Scala quasiquote 的两种用法会在result1
和之间给出不同的输出result2
?是否可以result3
使用 quasiquote 进行复制?即解析字符串内容并评估它?
import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._
val miniSrc = "val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"
val tree1 = q"$miniSrc"
//tree1: reflect.runtime.universe.Tree = "val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"
val tree2 = q"val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"
//tree2: reflect.runtime.universe.Tree =
//{
// val lst = 1.to(5).toList;
// val sum = lst.foldLeft(0)(((x$1, x$2) => x$1.$plus(x$2)));
// sum
//}
val tb = scala.reflect.runtime.currentMirror.mkToolBox()
val result1 = tb.eval(tree1)
//result1: Any = val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum
val result2 = tb.eval(tree2)
//result2: Any = 15
val result3 = tb.eval(tb.parse(miniSrc))
//result3: Any = 15