tags:

views:

1173

answers:

2
+6  Q: 

Scala Traits Usage

Can someone give explanation of Scala traits? I can't seem to find one anywhere.

Also, what are the advantages of traits over extending an abstract class?

+11  A: 

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 eachother 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
  }
}
André Laszlo
Here's the traits page from the Scala tour, it pretty much explains what traits are:http://www.scala-lang.org/node/126
André Laszlo
+2  A: 

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

agilefall