【问题标题】:Using Scala Macro Annotation in Intellij在 Intellij 中使用 Scala 宏注解
【发布时间】:2018-04-20 14:41:18
【问题描述】:

我正在尝试使用 scala 宏注释来简单地打印方法的返回值。我正在使用 Intellij 2017。这是代码:

class PrintResult extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro PrintResult.impl
}

object PrintResult {
  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val result = {
      annottees.map(_.tree).toList match {
        case q"$mods def $methodName(...$args): $returnType = { ..$body }" :: Nil => {
          q"""$mods def $methodName(...$args): $returnType =  {
            val res = {..$body}
            println($res)
            res
          }"""
        }
        case _ => c.abort(c.enclosingPosition, "Annotation @PrintResult can be used only with methods")
      }
    }
    c.Expr[Any](result)
  }
}

@PrintResult
object Test extends App {
    def add(a: Int, b: Int): Int = {
        a+b
    }
}

我将此配置添加到 sbt:

addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)

我还在 Intellij 运行配置中添加了 SBT 编译。

我收到此错误:

macro annotation could not be expanded (the most common reason for that is that you need to enable the macro paradise plugin; another possibility is that you try to use macro annotation in the same compilation run that defines it)

【问题讨论】:

  • 试试addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full),对我来说它在某些情况下会有所不同。
  • 顺便说一句,IntelliJ 与它无关,只有什么构建工具、Scala 版本和依赖项;)

标签: scala intellij-idea scala-macros


【解决方案1】:

引用错误信息:

另一种可能性是您尝试在定义它的同一编译运行中使用宏注释

object Test 必须在不同的子项目或src/test/scala 中(当PrintResultsrc/main/scala 中时)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多