2013-06-26 79 views
2

我在實現setter和getter方法時遇到了麻煩。這裏是一個例子:Scala getter/setter as macros

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 = "???" 
       ^

獲得者的作品,但二傳手沒有。它會產生奇怪的錯誤。

我意外地注意到了這樣的事情。如果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 = "???"未讀爲設定器。

有沒有我的錯誤?如何解決這個問題?

回答

3

哈哈,這是一個不錯的!我以爲我們發現了所有這些有趣的小錯誤,但顯然我們沒有。我代表您創建了一個錯誤:https://issues.scala-lang.org/browse/SI-7617

+0

已提交修正:https://github.com/scala/scala/pull/2689 –