【发布时间】:2016-10-27 09:29:20
【问题描述】:
我正在尝试编写一个简单的宏注释,它可以让我每次都为方法执行计时 - 如果我注释方法定义 - 或者如果我注释方法调用,则仅此一次。
注释方法定义工作得很好。不过
object Main {
def main(args:Array[String]): Unit ={
@MyMacro
doTest() //"Hello World"
}
}
似乎语法不正确。因为 intellij 抱怨在 :Unit ={ 之后它“期望”一个 },当我删除 @MyMacro 时,一个警告就会消失。
注释方法调用(或任意表达式,就此而言)的正确方法是什么?
(例如,我可能对获取所有对 getX 的调用的时间不感兴趣,但我可能想在代码中的某个特定位置测量花费的时间:
val x = @MyMacro getX()
)
更新
这行得通:
object Main {
def main(args:Array[String]): Unit ={
hello()
}
@MyMacro
def hello(): Unit ={
println("Hello World")
}
}
这不能编译:
object Main {
def main(args:Array[String]): Unit ={
hello(): @MyMacro
}
def hello(): Unit ={
println("Hello World")
}
}
因为
Error:(10, 15) 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)
hello(): @MyMacro
^
我只是用sbt 编译,使用
object BuildSettings {
val buildSettings = Defaults.defaultSettings ++ Seq(
version := "0.0.1",
scalaVersion := "2.11.8",
scalacOptions += "",
crossScalaVersions := Seq("2.10.2", "2.10.3", "2.10.4", "2.10.5", "2.10.6", "2.11.0", "2.11.1", "2.11.2", "2.11.3", "2.11.4", "2.11.5", "2.11.6", "2.11.7", "2.11.8"),
resolvers += Resolver.sonatypeRepo("releases"),
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)
)
}
object ScalaMacroDebugBuild extends Build {
import BuildSettings._
lazy val root: Project = Project(
"root",
file("."),
settings = buildSettings
) aggregate(macros, examples)
lazy val macros: Project = Project(
"macros",
file("macros"),
settings = buildSettings ++ Seq(
libraryDependencies <+= (scalaVersion)("org.scala-lang" % "scala-compiler" % _))
)
lazy val examples: Project = Project(
"examples",
file("examples"),
settings = buildSettings
) dependsOn(macros)
}
哪个应该同时解决这两个问题?
【问题讨论】:
标签: scala macros annotations sbt