0
我想寫一個簡單的宏註釋,讓我每次都可以讓方法執行 - 如果我註釋方法定義 - 或者只是這一次,如果我註釋一個方法調用。Scala - 宏註釋方法調用?
註釋方法定義工作得很好。然而,
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)
}
應採取的這兩個問題的關心?
嗯......我似乎遇到了一些麻煩(請參閱上面的編輯)。 – User1291
表達式上的宏註釋可能不被支持? http://docs.scala-lang.org/overviews/macros/annotations.html當然沒有提及它們:「用Scala認定爲宏的東西來標註任何頂層或嵌套的_definition_將使其擴展」; 「不僅適用於類和對象,還適用於任意_definitions_」。 –
真遺憾。所以我想如果我想要這種功能,我不得不尋找動態宏? – User1291