Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?
The short answer is that you can use multiple traits -- they are "stackable". Also, traits cannot have constructor parameters.
Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.
class Ball {
def properties(): List[String] = List()
override def toString() = "It's a" +
properties.mkString(" ", ", ", " ") +
"ball"
}
trait Red extends Ball {
override def properties() = super.properties ::: List("red")
}
trait Shiny extends Ball {
override def properties() = super.properties ::: List("shiny")
}
object Balls {
def main(args: Array[String]) {
val myBall = new Ball with Shiny with Red
println(myBall) // It's a shiny, red ball
}
}