Why can't a class extend traits with method of the same signature?
Solution 1
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"
}
Solution 2
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
Solution 3
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.
Solution 4
This is the diamond problem. Which method hi
should be inherited, the one from A, or the one from B? You can get around this as Don suggested, by using a common base trait.
IttayD
Updated on June 06, 2022Comments
-
IttayD almost 2 years
Why do I get the error below? How to workaround it?
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")}
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