动态特征差异从Scala 2.9到2.10

时间:2012-07-05 08:14:00

标签: scala

我编写了一小段代码来测试动态特征功能:

class Foo extends Dynamic {
  def selectDynamic(name: String) {
    println("selectDynamic: " + name)
  }
  def applyDynamic(name: String)(args: Any*) {
    println("applyDynamic: " + name)
  }
  def applyDynamicNamed(name: String)(args: (String, Any)*) {
    println("applyDynamicNamed: " + name)
  }
  def updateDynamic(name: String)(value: Any) {
    println("updateDynamic: " + name)
  }
}

object Test {
  def main(args: Array[String]) {
    val foo = new Foo
    foo.bar(5)     //1
    foo.bar(x = 5) //2
    foo.bar        //3
    foo.baz = 5    //4
  }
}

问题是它不能在Scala 2.9和2.10中编译,因为main中的第四行:

error: reassignment to val
foo.baz = 5

如果我评论这个字符串,2.9就会抱怨第二行:

error: not found: value x
foo.bar(x = 5)

同时2.10将编译,程序将产生:

applyDynamic: bar
applyDynamicNamed: bar
selectDynamic: bar

所以现在我想知道我做错了什么(可能会错过一些依赖项)? Scala 2.9和2.10中的Dynamic之间有区别吗?而foo.baz = 5

有什么问题

1 个答案:

答案 0 :(得分:6)