Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?
Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.
A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.
Abstract class contain constructor parameters. Traits are completely interoperable only when they do not contain any implementation code. Abstract class are completely interoperable with Java code. Traits are stackable. So, super calls are dynamically bound.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With