Updated April 12, 2023
Introduction to Scala Trait
Trait in Scala can be created by using trait keyword. Scala traits are like Interface in Java. They contain methods and field members. Method inside trait can be abstract and non-abstract and we can use these methods into different classes. But we cannot instiantie traits and it does not have constructor parameters. They basically are used to provide abstraction which provide us security and makes our application loosely coupled by making our service independent of user. We can use extend keyword to use this trait with different classes and provide implementation of unimplemented methods if needed. If we do not provide method body and type of variable then by default they will be abstract.
Syntax:
trait name{
// abstract method
// non abstract method and field members
}
In above syntax we can create raid by using trait keyword before the trait name. Inside trait we can define our methods and field members.
Example:
Code:
trait FirstTrait {
def message()
def message2()
}
In the above example we are defining two methods inside trait, but we have not yet provided them implementation.
So any class which is going to implement is responsible to provide the implementation of methods like below:
Code:
class FirstDemo extends FirstTrait{
def message()
{
println("first message : Hello from first method.")
}
def message2()
{
println("second message: Hello from second method.")
}
// method to create object and call methods.
object Main
{
def main(args: Array[String])
{
val object= new FirstDemo();
obj.message();
obj.message2();
}
}
Now we have given implantation of both the methods also we have main method from which we are going to call the method. Remember trait cannot be instiantied they do not have parameter constructor.
How does Trait work in Scala?
Basically the concept of traits used in object oriented programming language, they are like interface in java. In java interface are meant for abstraction. As we all know abstraction is the process by which hide the complexity from the user we are doing same here as well. Traits can be extended by using extends keyword. But we cannot create object of trait because they have no contractor. To provide implementation and to use the methods define in traits we can inherit trait by using classes and objects.
Traits contain abstract and non-abstract methods or we can say contain concrete methods. If we provide implementation of method inside a trait then it would be a non-abstract method, but if we only define a method inside a trait then it would be an abstract method. It also contains filed variables inside it. We can define a variable inside trait using var or val keyword provide by Scala. Suppose you have defined a variable using mentioned keyword but we have not yet initialize it then it would be abstract by default. The implementation of variable is also take care by the class itself which implements this trait same like methods.
Another point is, if we have defined one method inside trait and another class extending this trait but not providing its implementation then this class has to make itself abstract this is same as java.
Example:
Code:
trait Test{
def getDetail()
}
abstract class Demo extends Test{
def printDetail(){
// provide your logic.
}
}
So we make above Demo class as abstract because it is not providing body for trait method. So if a class those implements this Demo has to provide the method body and so on. This would be the same in case of variable also.
Now if a trait contain a method that is not abstract which means its implementation is already been defined in the trait then in this case then class which extend this trait do not need to provide the implementation of method.
Example:
Code:
trait Test {
def details(){
println("this method is already been defined in trait itself.");
}
}
Examples of Scala Trait
Given below are the examples mentioned:
Example #1
Here we will see how to use abstract method and provide their implementation and another class using extend keyword.
Code:
trait Flower {
def getColor()
}
class Rose extends Flower{
def getColor(){
println("Rose : are red in color!!")
}
}
class Amaryllis extends Flower{
def getColor(){
println("Amaryllis : are pink in color!!")
}
}
object Main{
def main(args:Array[String]){
var r = new Rose()
r.getColor()
var a = new Amaryllis()
a.getColor()
}
}
Output:
Example #2
It contains both abstract and non-abstract method inside a trait and we are calling them from main() function. We have not provided implementation for non – abstract method.
Code:
trait Flower {
def getColor()
def getMessage(){
println("This is flower trait!")
println("If you wannt to know abut specific color go implement this tarit.:)")
}
}
class Rose extends Flower{
def getColor(){
println("Rose : are red in color!!")
}
}
class Amaryllis extends Flower{
def getColor(){
println("Amaryllis : are pink in color!!")
}
}
object Main{
def main(args:Array[String]){
var r = new Rose()
r.getColor()
var a = new Amaryllis()
a.getColor()
println("caling non abstract method :: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
a.getMessage()
}
}
Output:
Example #3
This example contains field members also. We have initialize the filed at trait level only, but if you want you can define them with ‘var’ or’ val’ keyword and provide their implementation in extended class.
Code:
trait Flower {
def getColor()
def getMessage(){
println("This is flower trait!")
println("If you wannt to know abut specific color go implement this tarit.:)")
}
var v1: String = "Hello i am a variable"
var v2: String = "I am second variable."
def getDeatil(){
println("variable first :: " + v1)
println("variable second :: " + v2)
}
}
class Rose extends Flower{
def getColor(){
println("Rose : are red in color!!")
}
}
class Amaryllis extends Flower{
def getColor(){
println("Amaryllis : are pink in color!!")
}
}
object Main{
def main(args:Array[String]){
var r = new Rose()
r.getColor()
var a = new Amaryllis()
a.getColor()
println("caling non abstract method :: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
a.getMessage()
println("Field variables form trait are :: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
a.getDeatil()
}
}
Output:
Conclusion
Traits are like interface in java use to provide abstraction. They can we extend by using extends keyword but cannot be instantiated because they do not contain argument constructor.
Recommended Articles
We hope that this EDUCBA information on “Scala Trait” was beneficial to you. You can view EDUCBA’s recommended articles for more information.