在 Intellij 中使用 Scala 宏注解
Using Scala Macro Annotation in Intellij
我正在尝试使用 Scala 宏注释来简单地打印方法中的 return 值。我正在使用 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)
引用错误信息:
another possibility is that you try to use macro annotation in the same compilation run that defines it
object Test
必须在不同的子项目中或在 src/test/scala
中(当 PrintResult
在 src/main/scala
中)。
我正在尝试使用 Scala 宏注释来简单地打印方法中的 return 值。我正在使用 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)
引用错误信息:
another possibility is that you try to use macro annotation in the same compilation run that defines it
object Test
必须在不同的子项目中或在 src/test/scala
中(当 PrintResult
在 src/main/scala
中)。