The concept of traits is similar to an interface in Java, but they are even more powerful since they let you implement members. It is composed of both abstract and non-abstract methods, and it features a wide range of fields as its members. Traits can either contain all abstract methods or a mixture of abstract and non-abstract methods. In computing, a trait is defined as a unit that encapsulates the method and its variables or fields. Furthermore, Scala allows partial implementation of traits, but no constructor parameters may be included in traits. To create traits, use the trait keyword.
Syntax:
trait Trait_Name
{
// Fields...
// Methods...
}
Example:
trait MyCompany
{
def company
def position
}
class MyClass extends MyCompany
{
def company()
{
println("Company: Madanswer")
}
def position()
{
println("Position: SoftwareDeveloper")
}
def employee() //Implementation of class method
{
println("Employee: Aarav")
}
}
object Main
{
def main(args: Array[String])
{
val obj = new MyClass();
obj.company();
obj.position();
Obj.employee();
}
}
Output:
Company: Madanswer
Position: SoftwareDeveloper
Employee: Aarav