在Intellij中使用Scala宏注释

时间:2018-04-19 22:46:23

标签: scala intellij-idea scala-macros

我正在尝试使用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)

我还将SBT编译添加到Intellij运行配置中。

我收到此错误:

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)

1 个答案:

答案 0 :(得分:1)

引用错误消息:

  

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

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