这是一些使用Dynamic
. 如您所见,下面的部分按预期工作。
scala> import language.dynamics
import language.dynamics
scala> class ExpandoObject extends Dynamic {
| private val dict = collection.mutable.Map.empty[String, Any]
| def selectDynamic(name: String): Any = dict(name)
| def updateDynamic(name: String)(arg: Any) = dict(name) = arg
| }
defined class ExpandoObject
scala> val e = new ExpandoObject
e: ExpandoObject = ExpandoObject@14e03fec
scala> e.name = "rahul"
e.name: Any = rahul
scala> e.name
res62: Any = rahul
但是,当您在某个块中使用它时,它无法工作。
scala> {
| val e = new ExpandoObject
| e.name = "rahul"
| }
<console>:20: error: reassignment to val
e.name = "rahul"
^
scala>
同样,如果您updateDynamic
明确调用,它会起作用。
scala> {
| val e = new ExpandoObject
| e.updateDynamic("name")("rahul")
| e
| }
res66: ExpandoObject = ExpandoObject@3f755bd2
scala> res66.name
res67: Any = rahul
这是一个错误吗?或者我只是想念什么?