【问题标题】:Scala dynamic field named x名为 x 的 Scala 动态字段
【发布时间】:2012-06-07 16:23:40
【问题描述】:

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

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

以下工作正常且符合预期

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

打印'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 如此特别?我在做什么蠢事?

【问题讨论】:

  • 所以,我基本上必须忍受它,直到它真正从库中删除,而不仅仅是被弃用。耻辱。感谢您的指点 :-)
  • 这里有一个想法:假设 Dynamic 在尝试 selectDynamic 等之前首先尝试在范围内找到合适的名称。它是否也应该避免弃用名称?
  • 这听起来更像是一个 Scala 开发人员邮件列表的问题。但也许其他人可以通过对 Scala 的解析顺序更深入的了解来启发 SO 读者。
  • @hughleat 存在弃用周期是为了避免破坏取决于弃用内容的代码。如果解析顺序不同,代码就会中断。唉,我认为提出这个特殊情况并要求缩短正常的弃用周期是非常值得的,因为人们极不可能故意以这种方式使用x

标签: scala scala-2.10


【解决方案1】:

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

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

返回预期

res2: Symbol = 'x

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多