Home » Scala Trait

Scala Trait

A trait is like an interface with a partial implementation. In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods.

A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait. Any variable which is declared by using val or var but not initialized is considered abstract.

Traits are compiled into Java interfaces with corresponding implementation classes that hold any methods implemented in the traits.

Scala Trait Example

Output:

Hello  

If a class extends a trait but does not implement the members declared in that trait, it must be declared abstract. Let’s see an example.

Scala Trait Example


Scala Trait Example: Implementing Multiple Traits in a Class

If a class implements multiple traits, it will extend the first trait, class, abstract class. with keyword is used to extend rest of the traits.

You can achieve multiple inheritances by using trait.

Output:

This is printable  This is showable  

Scala Trait having abstract and non-abstract methods

You can also define method in trait as like in abstract class. I.e. you can treat trait as abstract class also. In scala, trait is almost same as abstract class except that it can’t have constructor. You can’t extend multiple abstract classes but can extend multiple traits.

Scala Trait Example

Output:

This is print method  This is show method  
Next TopicScala Trait Mixins

You may also like