我编写了一小段代码来测试动态特征功能:
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
?