Scala 宏 : Define Top Level Object

标签 scala scala-macros

我查看了 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/

相关文章:

Scala 宏 : What is the difference between typed (aka typechecked) and untyped Trees

scala - 如何在 "IF"中打印 "THEN"条件的源代码

scala - Scala宏:使用Scala中的类的字段制作 map

scala - 如何从传递给 scalatags 的事件处理程序访问 'this' 元素?

windows - 在 Windows 和 Apache Toree Kernel 上使用 Jupyter 以实现 Spark 兼容性

scala - 添加一些依赖项后,sbt 组装任务运行缓慢

Scala用var覆盖非抽象def

scala - 阅读 Parquet 时是否有可能保持列顺序?

scala - 在Scala中将方法提取到独立函数

scala - 这个 def 宏有什么问题?