Overview

In this article you will learn how to construct reusable parts of a program and deal with the tribulations of multiple inheritance.

A trait provides code reusability in Scala by encapsulating method and state and then offering the possibility of mixing them into classes thus allowing code reuse.

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.Let’s understand with below example.

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.

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 Test Trait This is Display Trait

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.

Output

This is print method This is show method

This is all about trait in Scala.Hope you like it.Keep Learning and Sharing!! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *