Why can't a class extend traits with method of the same signature?
Why is the error below? How to workaround it?
EDIT: 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 :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")} :4: error: method hi overrides nothing trait A {override def hi = println("A")}
EDIT: 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.hi B => nil
这在2.8和2.11中适用于我,并且可以让您在特质A
或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"
}
You could use a common base trait, say Base
, as follows:
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
With the type hierarchy the result of calling hi
's is as follows (note the use of {}
to instantiate the traits):
scala> (new A {}).hi
A
scala> (new B {}).hi
B
scala> (new C).hi
B
A trait adds methods to the class that mixes it in. If two traits adds the same method, the class would end up with two identical methods, which, of course, can't happen.
If the method is private in the trait, however, it won't cause problem. And if you want the methods to stack over each other, you may define a base trait and then abstract override
on the inheriting traits. It requires a class to define the method, however. Here is an example of this:
scala> trait Hi { def hi: Unit }
defined trait Hi
scala> trait A extends Hi { abstract override def hi = { println("A"); super.hi } }
defined trait A
scala> trait B extends Hi { abstract override def hi = { println("B"); super.hi } }
defined trait B
scala> class NoHi extends Hi { def hi = () }
defined class NoHi
scala> class C extends NoHi with B with A
defined class C
scala> new C().hi
A
B
If, however, you truly want two separate methods from each trait, then you'll need to compose instead of inherit.
链接地址: http://www.djcxy.com/p/51018.html上一篇: 自我有什么区别
下一篇: 为什么类不能用相同签名的方法扩展特征?