In this part of Scala blog series we’ll look at Traits, which is one of the great feature in Scala.
The main intention to use Traits is to implement reuse code segments in Scala. It can be thought of as interface that encapsulates method and field definitions. But it’s not necessary to provide implementation for all/some methods that the trait defines. Therefore, the implementation can be reuse to expand the class functionality by mixing them. Unlike class inheritance, in which one class must inherit from just one superclass, a class can extends and mix with any number of traits. Hence, we can also think the concept as multiple inheritance like in C# language.
If the methods don’t need arguments we can just declare the declaration name for the traits.
If method requires parameter, So the implementation goes as usual.
When extending one trait, use extends.
More than one traits, use extends for the class/first trait and with for subsequent traits.
If the methods are not implemented in the traits, it’s a must that we should implement the abstract traits methods.
Lets take a general example and try to understand much more clearly. See the following class diagram (Figure 1) that shows hierarchy of Animals.
The class hierarchy diagram clearly shows that we are maintaining our code segments separately and it allows scaling up/down since everything is independent.
Look at our Shark, Dolphin and Mermaid with a comprehensive analysis mind. I’m sure you will be able find out similar things in between each animal and the very unique behaviour/attribute of each animal. So to build up a animal we can use the traits to do the mixing to get the multiple behaviours/attributes. The following below code snippet disclose the features of traits.