问题
I looked type macros for scala. But when i would like create object from example, i got error:
Example.scala:7: `=', `>:', or `<:' expected
type Test(url: String) = macro impl
Example.scala:12: illegal start of simple expression
val clazz = ClassDef(..., Template(..., generateCode()))
Code:
//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 version: 2.10.2
From: type macros
回答1:
If only it were that easy! From the documentation you link to:
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.
And:
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.
So you're going to have to move to the Macro Paradise branch for 2.11 if you want this to work.
Note also that the ... in the type macros documentation is intended to indicate elided code—you can't just copy and paste it.
来源:https://stackoverflow.com/questions/17326661/scala-macro-define-top-level-object