Scala Trait Mixins

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.

You can use mixins in scala like this:


Scala Trait Example: Mixins Order Not Maintained

In this example, we have extended a trait and an abstract class. Let's see what happen.

Output:

error: class PrintA4 needs to be a trait to be mixed in
class A6 extends Print with PrintA4{
                            ^
one error found

The above program throws a compile time error, because we didn't maintain mixins order.


Scala Mixins Order

The right mixins order of trait is that any class or abstract class which you want to extend, first extend this. All the traits will be extended after this class or abstract class.

Scala Trait Example: Mixins Order Maintained

Output:

print sheet
Print A4 Sheet

Another Example of Scala Trait

Here, we have used one more approach to extend trait in our program. In this approach, we extend trait during object creation. Let's see an example.

Output:

print sheet
Print A4 Sheet




Latest Courses