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,

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

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

Notify of