Scala Traits by Code Example

We all might know about Java Interfaces. Traits in Scala are very much similar to Java Interfaces. There is just one exception if we compare traits with interfaces in Java (Java 7 and earlier version) and that is traits can also have methods with implementation. Let’s look from different perspective. In Scala we can treat traits same as classes which doesn’t have constructors with parameters.

Rules for defining Traits
  • Traits can have methods as well as variables
  • Traits may or may not have abstract methods
  • Traits doesn’t have constructor with parameters
  • One class can be extended from multiple traits using extend and with keywords
  • One class can also implement multiple traits using extend and with keywords

Let’s look at some examples,

//Trait can have abstract method
trait Flyable{
    def fly()
}

//Trait may not have any abstract method
trait Speakable{
    def makeNoice() = println("Generic Sound.....!!!!!")
}

//Trait can extand one or more traits
trait Quackable extends Speakable{

    //have to override method of parent  
    override def makeNoice() = println("Quack Quack.....!!!!!")

    def quack() = makeNoice
}   

//one class can extand multiple traits
class Duck extends Quackable with Flyable{
    def swim() = println("Duck is Swimming.....!!!!!")
    
    //have to override method of parent  
    override def fly() = println("Duck is Flying.....!!!!!")
}

object MainClass {
  def main(args:Array[String]){
    var duck = new Duck
    duck.swim
    duck.fly
    duck.makeNoice
    duck.quack
  }
}

Paste above code on Scala REPL and below output will be generated while executing it.

scala> MainClass.main(null)
Duck is Swimmming.....!!!!!
Duck is Flying.....!!!!!
Quack Quack.....!!!!!
Quack Quack.....!!!!!

Now the most common question same we typically have in Java,

What is the difference between trait and abstract class in Scala?

So here you go,

  • Same as Java you can extend only one class but can implement multiple traits in Scala
  • Abstract class may have constructor with parameters where as trait in Scala doesn’t support that
  • You can limit which classes can implement the traits
  • Abstract class of Scala are completely interpretable in Java where as traits of Scala can only be interpreted in Java if they don’t contain any implemented methods (this is not confirmed with Java 8)

When to use trait and abstract class in Scala?

  • Use trait if you just want to add some dynamic behaviour(s) in other class
  • Use abstract class if any entity is fully compatible with inheritance for class hierarchy

For example,
Tyre and RubberBall both are independent class and you want to add bouncing behaviour to both of these class than you should make Bouncable trait instead of abstract class as Bouncable cannot be a base class of above classes. They are not inherently compatible with Bouncable. Here you are adding new behaviour to your classes so it should be in the form of trait.

One interesting point here with abstract classes and traits is that both are stackable and provide modifications same as decorator pattern to underlying core classes or traits.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>