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

后端 未结 5 2145
旧时难觅i
旧时难觅i 2020-12-23 12:02

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 meth

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 12:48

    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.

提交回复
热议问题