19

This doesn't work:

trait Trait
class Class extends Trait with Trait

Compiler complains:

<console>:8: error: trait Trait is inherited twice
       class Class extends Trait with Trait
                           ^
<console>:8: error: trait Trait is inherited twice
       class Class extends Trait with Trait
                                      ^

This does:

trait Trait
class Abstraction extends Trait
class Implementation extends Abstraction with Trait

Questions:

  • Why does it work?
  • How is the second snippet different? (concerning the double inheritance issue)
  • Is the second snippet or pattern somehow useful?
agilesteel
  • 16,775
  • 6
  • 44
  • 55
  • Do you have a practical example where it is a real problem that the first doesn't work? – Jesper Aug 29 '11 at 13:43
  • 1
    The purpose of the question is not to find out why the first one does not work, but rather why the second one does. – agilesteel Aug 29 '11 at 13:46
  • 1
    Useful link: [chapter from Programming in Scala](http://www.artima.com/pins1ed/traits.html#i-1280910181-1) showing how linearization works. – 4e6 Aug 29 '11 at 13:52

1 Answers1

20

Second snippet works because of trait linearization. The compiler will organize the traits into a linear list so that Trait only appears once. I think the linearization is

Implementation, Trait, Abstraction, ScalaObject, AnyRef, Any

See this chapter from Programming Scala for a great explanation.

This is primarily done to have a consistent approach to the diamond inheritance problem and is useful in that case.

Since Trait cannot appear twice after linearization, it does not make sense to write Trait with Trait and it makes sense to be disallowed.

huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • Answer is very old so maybe scala changed this behaviour but for me right now it looks like this is wrong. Linearization should be: Implementation, Abstraction, Trait, ... – kpbochenek May 27 '15 at 20:14