我查看了 scala 的类型宏
。但是当我想从示例创建对象时,我收到错误:
Example.scala:7: `=', `>:', or `<:' expected
type Test(url: String) = macro impl
Example.scala:12: illegal start of simple expression
val clazz = ClassDef(..., Template(..., generateCode()))
代码:
//Example.sbt
object Example {
type Test(url: String) = macro impl
def impl(c:Context)(url: c.Expr[String]):c.Tree = {
import c.universe._
val name = c.freshName(c.enclosingImpl.name).toTypeName
val clazz = ClassDef(..., Template(..., generateCode()))
c.introduceTopLevel(c.enclosingPackage.pid.toString, clazz)
val classRef = Select(c.enclosingPackage.pid, name)
Apply(classRef, List(Literal(Constant(c.eval(url)))))
}
}
Scala 版本:2.10.2
来自:type macros
最佳答案
要是这么简单就好了!来自 the documentation您链接到:
Type macros are a pre-release feature included in so-called macro paradise, an experimental branch in the official Scala repository. Follow the instructions at the "Macro Paradise" page to download and use our nightly builds.
还有:
Please note that due to binary compatibility restrictions, macro paradise for 2.10.x doesn't include any features from macro paradise 2.11.x except for quasiquotes.
因此您将不得不移至 Macro Paradise如果您希望它起作用,请选择 2.11 的分支。
另请注意,类型宏文档中的 ...
旨在指示省略的代码 - 您不能只是复制并粘贴它。
关于Scala 宏 : Define Top Level Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326661/