不幸的是,最直观的方式,
val world = "Earth"
val tree = q"""println("Hello $world")"""
结果是
Error:(16, 36) Don't know how to unquote here
val tree = q"""println("Hello $world")"""
^
因为$
在 quasiquotes 内需要一个tree
.
val world = "Earth"
val tree = q"""println(${c.literal(s"Hello $world")})"""
有效,但是非常难看,并且我收到 Intellij 警告,该警告c.literal
已弃用,我应该改用 quasiquotes。
所以......我该怎么做?
更新
回应弗拉维安的评论:
import scala.language.experimental.macros
import scala.reflect.macros._
object TestMacros {
def doTest() = macro impl
def impl(c: blackbox.Context)(): c.Expr[Unit] = {
import c.universe._ //access to AST classes
/*
val world = "Earth"
val tree = q"""println(${c.literal(s"Hello $world")})"""
*/
val world = TermName("Earth")
val tree = q"""println("Hello $world")"""
tree match {
case q"""println("Hello Earth")""" => println("succeeded")
case _ => c.abort(c.enclosingPosition, s"huh? was: $tree")
}
c.Expr(tree) //wrap tree and tag with its type
}
}
给
Error:(18, 40) Don't know how to unquote here
val tree = q"""println("Hello $world")"""
^