Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing multiple traits in Scala

Quick note: Examples from the tutorial Scala for Java Refugees Part 5: Traits and Types.

Suppose I have the traits Student, Worker, Underpaid, and Young.

How could I declare a class (not instance), CollegeStudent, with all these traits?

Note: I am aware of the simplests cases, such as CollegeStudent with one or two Traits:

class CollegeStudent extends Student with Worker 
like image 539
Daniel Ribeiro Avatar asked Jul 05 '09 18:07

Daniel Ribeiro


People also ask

Can you extend multiple traits in Scala?

With Abstract and Non-Abstract Methods While we cannot extend multiple abstract classes, we can extend multiple traits in Scala.

What is trait mixing in Scala?

In scala, trait mixins means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class. It is necessary to maintain order of mixins otherwise compiler throws an error.

Does Scala support multiple inheritance?

Multiple Inheritance: In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Scala does not support multiple inheritance with classes, but it can be achieved by traits.

Which provides way to multiple inheritance in Scala?

Scala Trait: The Magnificent feature that enables Multiple Inheritance.


1 Answers

It is easy, when declaring a class you just use the "with" keyword as often as you want

class CollegeStudent extends Student with Worker with Underpaid with Young 

the order of the traits can be important if a trait is changing the behavior of the class, it all depends on traits you are using.

Also if you don't want to have a class which always uses the same traits you can use them later:

class CollegeStudent extends Student new CollegeStudent with Worker with Underpaid with NotSoYoungAnymore 
like image 165
Alexander Stolz Avatar answered Sep 21 '22 05:09

Alexander Stolz