Trait, an interface in Scala

Trait is the new Interface

Scala comes with a new keyword for interface called Trait. An Interface in Java helps us to declare methods and subsequently get implemented in classes. Similarly, Scala provides the same feature through Traits.
The syntax for declaring the traits goes with a keyword Trait before the name of the interface. The following snippet shows the example of Trait BaseDoor and the implementation of the same in a class. Here, implementation is done with extends keyword

trait BaseDoor{
 def open
 def close
 def lock
 def unlock
}
class FrontDoor extends BaseDoor

Strength of Traits over Interface

a) Method implementation in Interface

Traits comes with some more interesting features over Java interfaces. It’s not only allowing to declare methods but just like abstract class it also to allows implementation of methods. In Java the interfaces do not have method implementation. Only abstract class is allowed to have methods implemented, but Scala allows Traits to have implementation of the method. 
For instance, let us continue from the above example,
trait DoorDecors{
 def doorbell { println(“Ding! Dongggg!”)}
 def welcomeSign{println(“Welcome Home”)}
}
class FrontDoor extends BaseDoor with DoorDecors
Note: the keyword “with” is used for implementing more than one Trait to the class.

b) Abstract and Concrete fields
Traits allow to declare and define fields as abstract and concrete. If the fields are abstract then they have to be defined in the implemented class.

trait BaseDoor{
 var doorNumber:Int //abstract
 var thickNess = 2.5 //concrete
 var thickUnit:String = “inch” //concrete
}
class FrontDoor extends BaseDoor{
 var doorNumber = 11 //Initialization
 thickNess = 12 //Reassign
 thickUnit = “centimeter” //Reassign
}

Comments

Popular posts from this blog

Singleton class made easy in Scala

Quickstart with Angular 2/4