Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
912 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...