我正在尝试在 Scala 中实现类似C# 的ExpandoObject
类。这就是它应该如何工作:
val e = new ExpandoObject
e.name := "Rahul" // This inserts a new field `name` in the object.
println(e.name) // Accessing its value.
这是我到目前为止所尝试的:
implicit def enrichAny[A](underlying: A) = new EnrichedAny(underlying)
class EnrichedAny[A](underlying: A) {
// ...
def dyn = new Dyn(underlying.asInstanceOf[AnyRef])
}
class Dyn(x: AnyRef) extends Dynamic {
def applyDynamic(message: String)(args: Any*) = {
new Dyn(x.getClass.getMethod(message,
args.map(_.asInstanceOf[AnyRef].getClass) : _*).
invoke(x, args.map(_.asInstanceOf[AnyRef]) : _*))
}
def typed[A] = x.asInstanceOf[A]
override def toString = "Dynamic(" + x + ")"
}
class ExpandoObject extends Dynamic {
private val fields = mutable.Map.empty[String, Dyn]
def applyDynamic(message: String)(args: Any*): Dynamic = {
fields get message match {
case Some(v) => v
case None => new Assigner(fields, message).dyn
}
}
}
class Assigner(fields: mutable.Map[String, Dyn], message: String) {
def :=(value: Any): Unit = {
fields += (message -> value.dyn)
}
}
当我尝试编译此代码时,我得到一个StackOverflowError
. 请帮我完成这项工作。:) 谢谢。