Scala Traits
Examples
Stackable Modification with Traits
You can use traits to modify methods of a class, using traits in stackable fashion.
The following example shows how traits can be stacked. The ordering of the traits are important. Using different order of traits, different behavior is achieved.
class Ball {
def roll(ball : String) = println("Rolling : " + ball)
}
trait Red extends Ball {
override def roll(ball : String) = super.roll("Red-" + ball)
}
trait Green extends Ball {
override def roll(ball : String) = super.roll("Green-" + ball)
}
trait Shiny extends Ball {
override def roll(ball : String) = super.roll("Shiny-" + ball)
}
object Balls {
def main(args: Array[String]) {
val ball1 = new Ball with Shiny with Red
ball1.roll("Ball-1") // Rolling : Shiny-Red-Ball-1
val ball2 = new Ball with Green with Shiny
ball2.roll("Ball-2") // Rolling : Green-Shiny-Ball-2
}
}
Note that super is used to invoke roll() method in both the traits. Only in this way we can achieve stackable modification. In cases of stackable modification, method invocation order is determined by linearization rule.
Trait Basics
This is the most basic version of a trait in Scala.
trait Identifiable {
def getIdentifier: String
def printIndentification(): Unit = println(getIdentifier)
}
case class Puppy(id: String, name: String) extends Identifiable {
def getIdentifier: String = s"$name has id $id"
}
Since no super class is declared for trait Identifiable, by default it extends from AnyRef class. Because no definition for getIdentifier is provided in Identifiable, the Puppy class must implement it. However, Puppy inherits the implementation of printIdentification from Identifiable.
In the REPL:
val p = new Puppy("K9", "Rex")
p.getIdentifier // res0: String = Rex has id K9
p.printIndentification() // Rex has id K9