【问题标题】:Ambiguous reference to overloaded definition with inherited inner class, scala对具有继承内部类 scala 的重载定义的模糊引用
【发布时间】:2012-12-13 17:52:58
【问题描述】:

所以这是有问题的代码:

trait World {
  type State
  def dynamics(s: State): State
  // ...
}
trait GridWorld extends World {
  class State {...} // concrete
  def dynamics(s: State) = s    // concrete
  // some other staff still abstract
}
trait SimpleGridWorld extends GridWorld {
  class State extends super.State {...}  // concrete
  def foo {dynamics(new State)}  // compiler error
}

编译器说,dynamicsWorldGridWorld 中都匹配签名。但是,在World 中它是抽象的,然后在GridWorld 中实现,所以在我看来,很明显我在调用GridWorld.this.dynamics

我注意到的另一件事是,如果我删除SimpleGridWorld 中的extends super.State,一切正常(我不明白为什么,我确实需要GridWorld.State 中定义的功能)。有什么解释吗?谢谢!

更新 无论如何,我看到我的设计模式很奇怪,因为如果SimpleGridWorld 中的State 没有继承GridWorld.this.Statedynamics 将引用根特征World 中定义的未实现模式(这是有道理的,因为实现在GridWorld 中可能使用GridWorld.this.State 中可能不存在的SimpleGridWorld.this.State 的功能)。但我想要的是:

  1. XXXWorld.this.State 必须继承它的 super.State(或者直接使用它)
  2. dynamics 总是引用 super.dynamics 如果在超级特征/类中实现,除非在这里被覆盖。

我该怎么做?我认为这不是一个完全无关紧要的问题,可能上一个问题的答案会告诉我如何重新设计我的模式。

【问题讨论】:

    标签: scala inheritance overloading inner-classes ambiguous-call


    【解决方案1】:

    怎么样:

    trait World {
      type State
      def dynamics(s: State): State
    }
    trait GridWorld extends World {
      type State = MyState
      class MyState {} // concrete
      def dynamics(s: State) = s    // concrete
    }
    trait SimpleGridWorld extends GridWorld {
      class MyState extends super.MyState {}  // concrete
      def foo {dynamics(new MyState)}  // compiler error; ok
    }
    

    【讨论】:

    • 感谢回复,为什么还是编译错误?我试过了,它似乎有效,尽管我不认为 MyStateState 在概念上应该有不同的含义。
    • 嗯,我想多了,发现你的解决方案有些用心。 GridWorld 在类型层次结构中非常特殊,因为从那里开始,子类不再有 State==MyState。这是有道理的,因为GridWorld 是实现dynamics 的地方。只要我不在以后的课程中覆盖dynamics(我想过但也许不应该这样做),一切正常并且有意义。
    • 你可能想考虑类似Tour of Scala这篇文章并使用type State <: StateIf然后定义一个接口bass classabstract class StateIf
    • 这是我的最爱之一:stackoverflow.com/questions/10213395/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多