Sage-Code Laboratory
index<--

Scala Traits

Traits are reusable fragments of code. Think of traits like specification, contract or better sead requirements of implementation. A trait is not useful until it is implemented by a class. We use traits as a form of abstractization similar to Java interfaces.

Traits enable Scala to simulate multiple inheritance model. One class can extend a single other class but can extend multiple traits. This greatly improve code reusability. Let's see this model in a picture:

ScalaTraits

Multiple Inheritance

Syntax:

Next is scala "pseudo-code" that explain how to create a trait and how to use the trait to define a class. In next examples we will add more details to explain variations of base syntax.

//declare a simple trait
trait Trait_Name {
   // Variables
   ...
   // Methods
   ...
}

//using a trait previously defined
class Class_Name extends Trait_Name {
   // Variables
   ...
   // Methods
   ...
}

Abstract Methods

A trait usually contains a list of methods that have just the signature. That is an abstract method. These kind of methods must be implemented by a class or another sub-trait. There are traits that implement fully all methods. These are special!

Example:

//define first trait
trait Test1 {
   def sayHello(): Unit = {
     println("Hello Friend")
   }
}
//define second trait
trait Test2 {
   def todo(what: String): Unit //abstract
}

// this class extends two traits
class Demo() extends Test1 with Test2 {
  def todo(what: String) {
     println("You must " + what)
  }
}

// lets check out the new class Demo
object Main {
  def main(args: Array[String]): Unit = {
    val x = new Demo()
    x.sayHello()
    x.todo("wash dishes")
  }
}

Notes:


Read next: Collections