我正在尝试编写一个简单的宏注释,让我每次都可以对方法执行进行计时 - 如果我注释方法定义 - 或者只是一次注释方法调用。
注释方法定义可以正常工作。然而
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)
}
哪个应该处理这两个问题?
答案 0 :(得分:0)
An annotation of an expression e appears after the expression e, separated by a colon.
所以val x = getX(): @MyMacro
应该有用。