Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?
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
}
}
This site gives a good example of trait usage. One big advantage of traits is that you can extend multiple traits but only one abstract class. Traits solve many of the problems with multiple inheritance but allow code reuse.
If you know ruby, traits are similar to mix-ins
Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods.
Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods.
In contrast to classes, traits may not have constructor parameters. Traits are like classes, but which define an interface of functions and fields that classes can supply concrete values and implementations.
Traits can inherit from other traits or from classes.