我正在尝试创建一个将生成对象的Scala宏 - 类似于
object SomeEnum {
sealed abstract class Enum(name: String)
case object Option1 extends Enum("option1")
case object Option2 extends Enum("option2")
private val elements: Seq[Enum] = Seq(Option1, Option2)
def apply(code: String): Enum = {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我以为我可以创建一个宏createEnum,所以我可以放入
createEnum("SomeEnum", "Option1", "Option2")我的代码并让它生成.好像它正在呼唤一个宏.
但我不能理解宏.我正在使用Scala 2.11.6,只是为了尝试让某些东西工作,我创建了以下内容:
object createEnumObj {
def createEnumImpl(c: scala.reflect.macros.whitebox.Context)(ename: c.Expr[String]): c.universe.ModuleDef = {
import c.universe._
val Literal(Constant(s_ename: String)) = ename.tree
val oname = TermName(s_ename)
val barLine = q"val bar: Int = 5"
q"object $oname { $barLine }"
}
def …Run Code Online (Sandbox Code Playgroud)