Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros of using traits over abstract classes?

Tags:

scala

traits

Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?

like image 940
Zack Marrapese Avatar asked Aug 04 '09 20:08

Zack Marrapese


People also ask

What is the difference between a trait and 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.

Can a trait extend an abstract class?

A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.

What are abstract traits?

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.

Why do we use traits in Scala?

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.


2 Answers

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   } } 
like image 174
André Laszlo Avatar answered Oct 02 '22 16:10

André Laszlo


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

like image 24
agilefall Avatar answered Oct 02 '22 16:10

agilefall