In this blog post, we will talk about traits in Scala. Then we will discuss how is a trait different from abstract classes.

Scala Traits
A trait is similar to a partial implementation of an interface. A trait in Scala can contain abstract and non-abstract methods. We can make a trait with all abstract methods or some abstract methods and some non-abstract methods.
Variables declared in a trait with the val or var keywords are internally implemented in the class that implements the trait. Any variable that has been declared with val or var but has not been initialised is considered abstract.
Scala classes can also extend and “mix in” multiple traits.
Defining a Trait
To define a trait we require the trait keyword along with the name of the trait.
trait Pet
Now let’s take an example of extending a trait in a class for that we require to use the extends
keyword to extend a trait. Then implement any abstract members of the trait using the override
keyword
trait DomesticAnimal {
val name: String
}
class Animal(val name: String) extends DomesticAnimal
val dog = new Animal("Bruno")
val cat = new Animal("Snowbell")
We can also mix in multiple traits together and for that purpose we must
- Use
extends
to extend the first trait - Use
with
to extend subsequent traits
Abstract Classes
Scala also contains an abstract class notion, which is quite similar to Java’s abstract class concept. However, because traits are so effective, using an abstract class is rarely necessary.
In practice, an abstract class is only necessary when we want to create a base class that requires constructor arguments or when our Scala code will be called from Java code.
abstract class WildAnimal (name: String) {
def speak(): Unit = println("Roar..")
def eat(): Unit
}
class Animal(val name: String) extends WildAnimal {
override def speak() = println("Roar.. Roar..")
def eat() = println("Animal is eating")
}
How are traits different from abstract classes
- A trait support multiple inheritance whereas abstract classes do not. As we can extends only one class at a time, but can implement multiple traits.
- Traits generally do not contains constructor parameter unlike abstract classes.
- We can add a trait to an object instance but we can not do so with abstract classes.
- A trait is interoperable when it does not contain any implementation but abstract classes are normally interoperable with java code.
Conclusion
Thank you guys for making it to the end of the blog I hope you gained some knowledge about traits in Scala. Then, we learned about features of a trait and abstract classes. For other Scala related stuff you can check here.
Reference
For getting more knowledge regarding traits in Scala kindly refer to the following link