为什么类不能使用具有相同签名的方法扩展特征? [英] Why can't a class extend traits with method of the same signature?
本文介绍了为什么类不能使用具有相同签名的方法扩展特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么会出现以下错误?如何解决呢?
Why do I get the error below? How to workaround it?
我假设由于A和B编译为(接口,类)对,因此在编译C时选择正确的静态方法调用即可实现.我希望优先级是按顺序排列的.
I assumed that since A and B compile to (interface,class) pairs, it's a matter of choosing the right static method call to implement when compiling C. I would expect the priority to be according to order.
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")}
请注意,在Ruby中效果很好:
Note that in Ruby this works well:
>> 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
推荐答案
这在2.8和2.11中对我有效,并且允许您对特征A
或B
不打扰:
This works for me in 2.8 and 2.11, and would allow you to be non-intrusive in traits A
or B
:
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"
}
这篇关于为什么类不能使用具有相同签名的方法扩展特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文