我正在尝试将this answer从this question移植到scala-2.10。 这就是我试过的:
Macros.scala
package myProject.macros
import scala.reflect.macros.Context
import scala.language.experimental.macros
class LoggerImpl(val c: Context) {
import c.universe._
def getClassSymbol(s: Symbol): Symbol = if (s.isClass) s else getClassSymbol(s.owner)
def logImpl(msg: Expr[String]): Unit = {
val cl = getClassSymbol(c.enclosingClass.symbol).toString
// Do something with cl
// For this case cl should be "SomeObject"
}
}
object Logger {
def warning(msg: String): Unit = macro LoggerImpl.logImpl
}
XYZ.scala
package myProject.XYZ
import myProject.macros.Logger
object SomeObject {
def doSomething(...) = {
// Some operations
Logger.warning("sss")
}
}
但是当我尝试构建时,我遇到了这些错误:
[scalac-2.10] /../Macros.scala:20: error: not found: value LoggerImpl
[scalac-2.10] def warning(msg: String): Unit = macro LoggerImpl.logImpl
[scalac-2.10] ^
[scalac-2.10] /../XYZ.scala:18: error: not found: value LoggerImpl
[scalac-2.10] def warning(msg: String): Unit = macro LoggerImpl.logImpl
[scalac-2.10] ^
[scalac-2.10] two errors found
我查看了this example,如果它们位于不同的包中,是否有办法让宏工作?
答案 0 :(得分:0)
你可以试试这个:
object LoggerImpl {
def logImpl(c: Context)(msg: c.Expr[String]): c.Expr[Unit] = {
import c.universe._
def getClassSymbol(s: Symbol): Symbol = if (s.isClass) s else getClassSymbol(s.owner)
val cl = getClassSymbol(c.enclosingClass.symbol).toString
// Do something with cl
// For this case cl should be "SomeObject"
}
}
不幸的是我手边还没有scala 2.10,但我认为上面的内容应该对你有用,因为你的代码也不能为scala 2.11编译,而且10和11的实现似乎没有太大差别
请注意,您需要返回c.Expr[Unit]
才能执行任何操作,还需要在单独的模块中编译它 - 最后一个是scala宏的要求