Scala multiple inheritance with classes

Why doesn't Scala support multiple inheritance with regular classes? can we not apply the same linearization logic that we apply to traits that can be used for classes? This should be possible since Python implements multiple inheritance (with normal classes) using C3 Linearization.

+3


source to share


2 answers


I don't know about Python, but IMO, the difference between trait and class is constructor.

The constructor has many limitations compared to the conventional method. For example, they can be called only once for each object, they need to be called for each new object, and the constructor of a child class must call its parent constructor.

                       A
                     /   \    
                    /     \
                   B       C
                    \     /
                     \   /
                       D

      



Now, the famous problem with diamonds. If B and C inherits from A and D inherits from B and C, then A's constructor will be called twice. As opposed to choosing the implementation of the traits methods, it is necessary to call the constructors B and C, which, in turn, must call the constructor A.

Traits avoid this problem as they don't have constructors.

+8


source


Scala doesn't need classes at all. You can only have traits with constructors and be with them.



The only reason it has classes is for compatibility with the underlying host framework. And most Scala platforms want to work (Java, .NET, Objective-C / Cocoa, ECMAScript) only support one inheritance for classes (or prototypes in ECMAScript).

+1


source







All Articles