Scala Traits
Scala Tutorial
Overview
Traits can be thought of as interfaces in which it’s possible, but not necessary, to provide implementations for all or some of the methods.
Like class, a trait encapsulates method and field definitions.
A trait provides code reusability in Scala by offering the possibility of mixing it into classes thus allowing code reusability.
Classes and objects can extend traits but traits cannot be instantiated and therefore have no parameters — Upcoming Scala 3 will support accepting parameters.
// Won't compile as traits don't allow constructor parameters
trait Person (name: String)
One trait can extend another trait.
A trait can also extend a class.
Unlike abstract classes, traits can be used as mixin.
Using Traits
Use the “extends” keyword to extend a trait.
Implement any abstract members of the trait using the override keyword.
If a class extends a trait but does not implement all the methods defined in that trait, the class must be declared abstract.
abstract class Implementer extends SomeTrait {...}
If a class implements multiple traits, it will extend
the first trait and then use with
for other traits.
class Dog extends Animal with WaggingTail with FourLeggedAnimal {
// implementation code here ...
}
Abstract and concrete fields in traits
In a trait, define a field with an initial value to make it concrete, otherwise give it no initial value to make it abstract.
trait PizzaTrait {
var numToppings: Int // abstract
val maxNumToppings = 10 // concrete
}
What Traits can’t do?
- Traits cannot be instantiated.
- Traits don’t allow constructor parameters.
Inter-operable with Java
Traits are fully inter-operable only if they do not contain any implementation code.
When to consider Trait?
TODO
Scala Exercises: https://github.com/SenthilNayagan/scala-tutorial