Scala getter / setter as macros

时间:2013-06-26 15:39:13

标签: scala macros getter-setter scala-macros

我无法将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 = "???"未被视为setter。

我有错吗?如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

哈哈,这是一个很好的!我以为我们已经找到了所有这些有趣的小错误的宏,但显然我们没有。我代表您创建了一个错误:https://issues.scala-lang.org/browse/SI-7617