Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Scala class extend multiple classes?

Tags:

scala

Is it possible to extend multiple classes in Scala.

For example if I have ClassA and ClassB then can ClassC extend ClassA and ClassB (like in C++).

like image 680
Maksim Avatar asked Mar 29 '12 04:03

Maksim


People also ask

Can you extend a class in Scala?

To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala : To override method in scala override keyword is required. Only the primary constructor can pass parameters to the base constructor.

Can we extend multiple traits in Scala?

A Scala class can extend multiple traits at once, but JVM classes can extend only one parent class. The Scala compiler solves this by creating "copies of each trait to form a tall, single-column hierarchy of the class and traits", a process known as linearization.

Why we Cannot extend multiple classes?

When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance.


2 Answers

You can't extend multiple classes, but you can extend several traits. Unlike Java interfaces, traits can also include implementation (method definitions, data members, etc.). There is still a difference in that you can't instantiate a trait directly (similar to abstract classes in a way).

trait T1 trait T2 trait T3 class C extends T1 with T2 with T3 
like image 180
Tal Pressman Avatar answered Oct 05 '22 15:10

Tal Pressman


No, ClassC just can extend one of those, but you can mixin multiple traits.

like image 35
loki Avatar answered Oct 05 '22 15:10

loki