Traits enable Scala to simulate multiple inheritance model. One class can extend a single other class but can extend multiple traits. This greatly improve code reusability. Let's see this model in a picture:
Multiple Inheritance
Next is scala "pseudo-code" that explain how to create a trait and how to use the trait to define a class. In next examples we will add more details to explain variations of base syntax.
//declare a simple trait
trait Trait_Name {
// Variables
...
// Methods
...
}
//using a trait previously defined
class Class_Name extends Trait_Name {
// Variables
...
// Methods
...
}
A trait usually contains a list of methods that have just the signature. That is an abstract method. These kind of methods must be implemented by a class or another sub-trait. There are traits that implement fully all methods. These are special!
//define first trait
trait Test1 {
def sayHello(): Unit = {
println("Hello Friend")
}
}
//define second trait
trait Test2 {
def todo(what: String): Unit //abstract
}
// this class extends two traits
class Demo() extends Test1 with Test2 {
def todo(what: String) {
println("You must " + what)
}
}
// lets check out the new class Demo
object Main {
def main(args: Array[String]): Unit = {
val x = new Demo()
x.sayHello()
x.todo("wash dishes")
}
}
Read next: Collections