Suppose you have defined a variable using mentioned keyword but we have not yet initialize it then it would be abstract by default. We can define a variable inside trait using var or val keyword provide by Scala. It also contains filed variables inside it. 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. Traits contain abstract and non-abstract methods or we can say contain concrete methods. To provide implementation and to use the methods define in traits we can inherit trait by using classes and objects. But we cannot create object of trait because they have no contractor. Traits can be extended by using extends keyword. As we all know abstraction is the process by which hide the complexity from the user we are doing same here as well. In java interface are meant for abstraction. How does Trait work in Scala?īasically the concept of traits used in object oriented programming language, they are like interface in java.
![scala trait scala trait](https://image.slidesharecdn.com/scalatraits-aug24-introduction-130901094509-phpapp02/95/scala-traits-aug24introduction-2-638.jpg)
Remember trait cannot be instiantied they do not have parameter constructor.
![scala trait scala trait](https://cdn.educba.com/academy/wp-content/uploads/2020/05/Scala-Trait.jpg)
Now we have given implantation of both the methods also we have main method from which we are going to call the method. method to create object and call methods. Println("second message: Hello from second method.") Println("first message : Hello from first method.") So any class which is going to implement is responsible to provide the implementation of methods like below:
![scala trait scala trait](https://image.slidesharecdn.com/traitsinscala-130527062246-phpapp02/95/traits-in-scala-11-638.jpg)
In the above example we are defining two methods inside trait, but we have not yet provided them implementation. Inside trait we can define our methods and field members. In above syntax we can create raid by using trait keyword before the trait name.
#Scala trait software
Web development, programming languages, Software testing & others Start Your Free Software Development Course