Should we always use `override` in Trait

Should we always use override

Trait to eliminate the diamond inheritance problem?

Let's see an example to explain the point:

trait S { def get : String }
trait A extends S { override def get = "A" }
trait B extends S { override def get = "B" }
class C extends A with B

      

Without, the override

following won't compile.

+3


source to share


1 answer


Using override

will make it compile, but the real question is, what are you trying to achieve?

In scala, the properties you extend are linearized. It means that

class C extends A with B
new C().get

      

will create "B"

but



class C extends B with A
new C().get

      

will produce "A"

instead.

And what do you expect? Generally speaking, depending on the order of inheritance, it seems like a scary design choice to solve the diamond problem (although there is a legitimate use of this language feature such as the pattern with pattern)

So back to your original question, should you always use an override? No, you just have to avoid diamonds in your inheritance hierarchies.

+10


source







All Articles