5

只需实现一个动态对象(使用 2.10.0-M3):

import language.dynamics
object D extends Dynamic {
    def selectDynamic( field : String ) = Symbol( field )
}

以下工作正常且符合预期

object DynamicTest extends App {
    println( D.a )
}

打印'一个

但是,如果我尝试这个:

object DynamicTest extends App {
    println( D.x )
}

我得到令人讨厌的错误:

[error] DynProb.scala:7: type mismatch;
[error]  found   : D.type
[error]  required: ?{val x: ?}
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error]  both method any2Ensuring in object Predef of type [A](x: A)Ensuring[A]
[error]  and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
[error]  are possible conversion functions from D.type to ?{val x: ?}
[error]     println( D.x )
[error]              ^
[error] one error found

为什么 x 如此特别?我在做傻事吗?

4

1 回答 1

0

我现在想出了一个简单的解决方案:

import language.dynamics
object D extends Dynamic {
    def selectDynamic( field : String ) = Symbol( field )
    def x = selectDynamic("x")
}
D.x

返回预期的

res2: Symbol = 'x

我很想重新定义一个名为的特征CompleteDynamic来覆盖这个“x”变量,但我暂时不能。

于 2013-10-07T08:17:07.443 回答