为什么类不能使用相同签名的方法扩展特征?

Itt*_*ayD 27 overriding scala traits

为什么下面的错误?如何解决它?

编辑:我假设因为A和B编译成(接口,类)对,所以在编译C时选择正确的静态方法调用是一个问题.我希望优先级按顺序排列.

scala> trait A { def hi = println("A") }
defined trait A

scala> trait B { def hi = println("B") }
defined trait B

scala> class C extends B with A
<console>:6: error: error overriding method hi in trait B of type => Unit;
 method hi in trait A of type => Unit needs `override' modifier
       class C extends B with A

scala> trait A { override def hi = println("A") }
<console>:4: error: method hi overrides nothing
       trait A {override def hi = println("A")}
Run Code Online (Sandbox Code Playgroud)

编辑:注意在Ruby中这很好用:

>> module B; def hi; puts 'B'; end; end
=> nil
>> module A; def hi; puts 'A'; end; end
=> nil
>> class C; include A; include B; end
=> C
>> c = C.new
=> #<C:0xb7c51068>
>> c.hi
B
=> nil
Run Code Online (Sandbox Code Playgroud)

Mit*_*ins 52

这在2.8和2.11中适用于我,并且允许您在特征中具有非侵入性AB:

trait A { def hi = println("A") }
trait B { def hi = println("B") }

class C extends A with B {
  override def hi = super[B].hi
  def howdy = super[A].hi // if you still want A#hi available
}

object App extends Application {
  (new C).hi // prints "B"
}
Run Code Online (Sandbox Code Playgroud)

  • 优秀!太糟糕了,如果我尝试'C级扩展A与B',错误没有提到这种解决冲突的方式. (3认同)

Don*_*zie 12

你可以使用一个共同的基本特征,Base如下所示:

trait Base {def hi: Unit}
trait A extends Base {override def hi = println("A")}
trait B extends Base {override def hi = println("B")}
class C extends A with B
Run Code Online (Sandbox Code Playgroud)

对于类型层次结构,调用的结果hi如下(注意使用{}实例化特征):

scala> (new A {}).hi
A

scala> (new B {}).hi
B

scala> (new C).hi
B
Run Code Online (Sandbox Code Playgroud)