A Trait is a concept of object-oriented programming that can extend the functionality of a class using a set of methods. Traits are similar to interfaces in Java programming language. Trait can’t be instantiated and has no arguments or parameters. We can use extend Trait using classes and objects. Traits can have both abstract and non-abstract methods, fields as their members. When we do not initialize a method in a trait then it is called abstract and the one which is initialized is called non-abstract.
Scala Trait Syntax
The syntax for the Scala Trait is upfront and looks similar to a class the only difference is that in the place of class we write down the Trait followed by the name of the Trait.
Let us create a Trait with the below example.
trait Trait_Name{
// Variables
// Methods
}
Output
Scala Trait with Abstract method
We will define a trait named Scala_Trait_example, which will be inherited by the class cloudduggu. Inside the Trait, we will define an abstract method called scala(), which will be defined in the cloudduggu class. In this example scala()method is an abstract method, and hence, the declaration is made in the class which inherited trait.
Let us create Trait with Abstract method.
trait Scala_Trait_example{
def scala()
}
class cloudduggu extends Scala_Trait_example{
def scala(){
println("Cloudduggu is a BigData and Cloud Tutorial Website.")
}
}
object Main{
def main(args:Array[String]){
var a = new cloudduggu()
a.scala()
}
}
Output
Click Here To Download Code File.
Scala Trait with Non-Abstract method
In the previous example, we had the scala() abstract method. In this example, we will see an example of a non-abstract method in which the class which extends trait need not implement the method which is already implemented in a trait.
Let us create a Trait with the non-abstract method.
trait Ferrari{
// trait variables
var make: String = "Ferrari"
var model: String = "GTC4Lusso"
var fuel: Int = 40
// trait method: NON-ABSTRACT
def Display() {
println("Make of the Car : " + make);
println("Model of the Car : " + model);
println("Fuel capacity of the Car : " + fuel);
}
}
class Car extends Ferrari{
// class variables
var make1: String = "Land Rover"
var model1: String = "SWB Vogue"
var fuel1: Int = 85
// Class method
def Land_Rover_Specs() {
println("Make of the Car : " + make1);
println("Model of the Car : " + model1);
println("Fuel capacity of the Car : " + fuel1);
}
}
object Main {
// Main method
def main(args: Array[String])
{
// Class object
var obj = new Car();
println("Calling the Class Method")
obj.Land_Rover_Specs();
println("Calling the Trait Method")
obj.Display();
}
}
Output
Click Here To Download Code File.