我听说Dynamic在某种程度上可以在Scala中进行动态类型化.但我无法想象这可能是什么样子或它是如何工作的.
我发现一个人可以继承特质 Dynamic
class DynImpl extends Dynamic
Run Code Online (Sandbox Code Playgroud)
该API称,可以使用这样的:
foo.method("blah")~~> foo.applyDynamic("method")("blah")
但是当我尝试它时它不起作用:
scala> (new DynImpl).method("blah")
<console>:17: error: value applyDynamic is not a member of DynImpl
error after rewriting to new DynImpl().<applyDynamic: error>("method")
possible cause: maybe a wrong Dynamic method signature?
(new DynImpl).method("blah")
^
Run Code Online (Sandbox Code Playgroud)
这是完全合乎逻辑的,因为在查看来源之后,事实证明这个特征是完全空的.没有applyDynamic定义方法,我无法想象如何自己实现它.
有人能告诉我我需要做些什么才能让它发挥作用吗?
如何在运行时定义新类型?我有一个工厂方法需要this.type 使用标记接口创建一个新实例.标记接口在编译时未混合.我需要找到一种在运行时执行此操作的方法.
我正在使用Scala,但我认为答案将足以涵盖Java和Scala.
trait Fruit {
def eat: this.type with Eaten = {
getClass.getConstructors()(0).newInstance(Array()).asInstanceOf[this.type];
// somehow this needs to return a new instance of this.type with the Eaten trait
// note that "Apple with Eaten" is not a type that exists at compile-time
}
}
trait Eaten // marker interface
class Apple extends Fruit
val apple1 = new Apple
val apple2 = a.eat // should return a new Apple with Eaten instance
def eater(eaten: Eaten) = …Run Code Online (Sandbox Code Playgroud)