Search code examples
scaladiamond-problem

Should we always use `override` in Trait


Should we always use override in Trait to solve preemptively the diamond inheritance issue ?

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 override, the following doesn't compile.


Solution

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

    In scala, traits you're extending from are linearized. This means that

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

    will produce "B"

    but

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

    will produce "A" instead.

    So what do you expect? Generally speaking, depending on the order of the inheritance for solving the diamond problem seems like a terrible design choice (while there are legitimate uses of this language feature, like the stackable trait pattern)

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