Why can't a class extend traits with method of the same signature?

房东的猫 提交于 2019-11-29 20:27:22
Mitch Blevins

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"
}
Don Mackenzie

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.

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.

I had the same problem and I didn't like to have to create an intermediary trait because I can have 4,5 or even 6 traits with the same methods, because it is traits containing CRUD operations (find, create...). Furthermore I needed to use those trait together only for test purpose and I always try to avoid as much as possible to modify the structure of my project only to make my test easier. So I simply implemented those traits in different objects :

class somethingToTest {
  object AImpl extends ATrait 
  object BImpl extends BTrait

  val a = AImpl.methodDuplicated()
  val b = BImpl.methodDuplicated()
}

It is probably not the most clever way to use traits but it doesn't require any change in the project's code, it only implies to have a bit more code in the tests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!