【问题标题】:Inheritance of same name method from difference traits从不同特征继承同名方法
【发布时间】:2016-10-25 13:46:21
【问题描述】:

我有一个 trait 扩展了另外两个具有相同名称的函数的特征,但它与内部有点不同,我想知道如何知道将调用哪个函数?

我有 Bprint()Cprint(),如果我像这样继承它们:

trait A extends B with C {
    def print()
}

每个打印打印其他内容,将调用哪个打印?

【问题讨论】:

    标签: java scala inheritance traits


    【解决方案1】:

    在您遇到名称冲突的特定情况下,您将收到编译时错误。假设D 是实现类:

    class D extends A with C with B
    
    def main(args: Array[String]): Unit = {
      val d = new D
      println(d.print())
    }
    

    你会看到:

    Error:(25, 9) class D inherits conflicting members:
      method print in trait B of type ()Unit  and
      method print in trait C of type ()Unit
    (Note: this can be resolved by declaring an override in class D.)
      class D extends A with B with C
    

    但是,如果我们通过将override print() 添加到D 来帮助编译器,并使其调用super.print(),它将打印支持print 方法的行列中的最后一个特征,即:

    trait A { }
    
    trait B { def print() = println("hello") }
    
    trait C { def print() = println("world") }
    
    class D extends A with B with C {
      override def print(): Unit = super.print()
    }
    

    我们会得到“世界”。如果我们切换BC

    class D extends A with C with B {
      override def print(): Unit = super.print()
    }
    

    我们会得到“你好”。

    【讨论】:

    • 我只想补充一点,您可以明确表示:class D extends A with B with C { override def print(): Unit = super[B].print() }
    【解决方案2】:

    原始 Schärli、Ducassé、Nierstrasz、Black 纸中的 Traits 最重要的特征之一是通过重命名和隐藏来解决冲突。 Scala 的 Traits 中完全没有此功能。

    在 Scala 中,根本不允许发生冲突。它们被类型系统检测并拒绝。 (最初的论文是在 Smalltalk 的上下文中,它没有类型系统,所以使用了不同的方法。)

    【讨论】:

      【解决方案3】:

      Scala 编译器给你编译错误。

      您为什么不自己使用 Scala REPL 来看看呢。

      scala> trait B { def print(): Unit = println("B") }
      defined trait B
      
      scala> trait C { def print(): Unit = println("C") }
      defined trait C
      
      scala> trait A extends B with C { def foo = print() }
      cmd11.sc:1: trait A inherits conflicting members:
        method print in trait B of type ()Unit  and
        method print in trait C of type ()Unit
      (Note: this can be resolved by declaring an override in trait A.)
      trait A extends B with C { def foo = print() }
            ^
      Compilation Failed
      

      我想你可以很容易理解使用编译器错误

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 2021-12-19
        • 2013-12-21
        • 2020-11-13
        • 2018-04-11
        相关资源
        最近更新 更多