Monday, 4 August 2014

Scala Note 2: Trait v.s. Interface v.s. Class


Two main usages of traits: turning a thin interface into a rich one; provide stackable modifications to classes.
In Scala, a class can only have one superclass. Classes, objects and traits can inherit from at most one class but arbitrary many traits.
A trait is declared like an abstract class, just with 'trait' instead of 'abstract' class.
Traits are used to define object types by specifying the signature of the supported methods. 
Unlike Java, Scala allows traits to be partially implemented
In contrast to classes, traits may not have constructor parameters.

Traits resemble interfaces in Java, but are more powerful 

1. Trait can contains both fields and concrete methods, While interface contains only method signature without concrete implementation.

2. To mix in a Trait, use either "extends" or "with" instead of "implements" for interface. Use "override" keyword to override a method. If a trait is not the only parent of a class, use "extends" to indicate the superclass(the first parent), and "with" to mix in a trait.

3. Scala can mix in a trait during instantiation.


For example:

  1. trait Friendly {  
  2.   def greet() = "Hi"
  3. }
  4. class Dog extends Friendly {  
  5.   override def greet() = "Woof"  
  6. }
  1. pet = new Dog extends Friendly 
  2. println(pet.greet())

Difference between trait and class

On the other hand, traits cannot have any "class" parameters(the ones passed to the primary constructor of a class) ,  only classes can, e.g class Point(x:Int, y:Int)


Use an abstract class instead of a trait when the base functionality must take constructor parameters. However, be aware that a class can extend only one abstract class.

In classes, super calls are statically bound, in traits, they are dynamically bound.

No comments:

Post a Comment