我无法将 setter 和 getter 方法实现为宏。这是一个例子:
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.reflect.macros.Context
import scala.language.experimental.macros
object ValueMacro {
def getValueImpl[T](c: Context): c.Expr[T] = {
import c.universe._
c.Expr[T](Apply(Select(c.prefix.tree, newTermName("getVal")), Nil))
}
def setValueImpl[T](c: Context)(value: c.Expr[T]): c.Expr[Unit] = {
import c.universe._
c.Expr[Unit](Apply(Select(c.prefix.tree, newTermName("setVal")), List(value.tree)))
}
}
object Module {
def setVal(value: String): Unit = ???
def getVal(): String = ???
def value: String = macro ValueMacro.getValueImpl[String]
def value_=(value: String): Unit = macro ValueMacro.setValueImpl[String]
}
// Exiting paste mode, now interpreting.
import scala.reflect.macros.Context
import scala.language.experimental.macros
defined module ValueMacro
defined module Module
scala> Module.value
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:252)
...
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
scala> Module.value = "???"
<console>:11: error: reassignment to val
Module.value = "???"
^
Getter 有效,但 setter 无效。它会产生奇怪的错误。
无意间我注意到了这样的事情。如果模块中不存在 getVal() 则
scala> Module.value
<console>:15: error: value getVal is not a member of object Module
Module.value
^
scala> Module.value = "???"
<console>:17: error: value getVal is not a member of object Module
val $ires2 = Module.value
^
<console>:14: error: value getVal is not a member of object Module
Module.value = "???"
^
看起来不像Module.value = "???"
二传手。
有我的错误吗?如何解决这个问题?