Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

10. Traits

10.1. Overview

Traits are similar to abstract classes you can also use them to define methods and variables. The difference is that every class in Scala can only extends one class (abstract or normal) but and can can extend / implement as many traits as it wants. By this Scala allows "multiple inheritance".

Scala multiple inheritance is safe, e.g. it doesn't have the so-called diomond problem. Scala solve this problem by a linearisation of the call path for the methods. So even if two traits implement the same method it is clean which one is called if a class implements both.

To use the trait the class extends the first trait and the other are used with the keyword "with". If the class already extends another class you use directly the keyword with.

10.2. Example

Create a Scala project "de.vogella.scala.traits".

Create the following coding.

				package de.vogella.scala.traits

trait MyTrait {
	def sayHello() = println("Hello from MyTrait")
}

			

				package de.vogella.scala.traits

trait MyTrait2 {
    def sayHello() = println("Hello from MyTrait2")
	def sayHello2() = println("Hello2 from MyTrait2")
}

			

				package de.vogella.scala.traits

object TraitTest extends MyTrait with MyTrait2 {

  def main(args: Array[String]) = {
	  sayHello
	  sayHello2
  }
}

			

Scala provides several pre-defined traits which can be used. For example the "Ordered" Trait defines the method compare as abstract which the client needs to implement. The "Ordered" Trait pre-define the compare operations which can then be used directly.