Trait
Properties:
• Trait in scala have lot of similarities with Interface in java,but Trait is more powerfull than
Interface because Trait allows to implement members wititn it.
• Trait is a combination of abstract and and Non-abstract methods.
• Trait can not be instansiated and thus it have no parameters.
• Trait can be extended by other traits,abstract classes,concrete classes and case classes as
well.
• Traits can be use to achieve Multiple Inheritance in scala,so Diamond problem of Multiple
Inheritance solved by linearization usin Traits.
Trait Defination looks like a Class defination with “trait” Keyword.
Syntax : trait Trait_Name{
//Fields
//Methods
}
For Example :
trait Calculator{
def doAddition(num1:Int,num2:Int) = {
num1+num2
}
def doSubtraction(num1:Int,num2:Int)
}
In given example,Trait “Calculator” is defined with concrete Method “doAddition” and Abstract
method “doSubtraction”.
Once Trait defined it can be mixed in Class by using “extends” or “with” keywords.
class CalculatorOperation extends Calculator{
def doSubtraction(num1:Int,num2:Int):Int=
{
num1-num2
}
}
After this,you can call methods in Trait and Class by creating instance of Class CalculatorOperation
in Singleton Object or in the Main method.
When a class inherits multiple traits then use extends keyword before the first trait and after that use
with keyword before other traits.
Syntax-
Class Class_Name extends TraitName-1 with TaitName-2 with TraitName-3
{
//Body of Class
}

Trait blog

  • 1.
    Trait Properties: • Trait inscala have lot of similarities with Interface in java,but Trait is more powerfull than Interface because Trait allows to implement members wititn it. • Trait is a combination of abstract and and Non-abstract methods. • Trait can not be instansiated and thus it have no parameters. • Trait can be extended by other traits,abstract classes,concrete classes and case classes as well. • Traits can be use to achieve Multiple Inheritance in scala,so Diamond problem of Multiple Inheritance solved by linearization usin Traits. Trait Defination looks like a Class defination with “trait” Keyword. Syntax : trait Trait_Name{ //Fields //Methods } For Example : trait Calculator{ def doAddition(num1:Int,num2:Int) = { num1+num2 } def doSubtraction(num1:Int,num2:Int) } In given example,Trait “Calculator” is defined with concrete Method “doAddition” and Abstract method “doSubtraction”. Once Trait defined it can be mixed in Class by using “extends” or “with” keywords. class CalculatorOperation extends Calculator{ def doSubtraction(num1:Int,num2:Int):Int= { num1-num2 } } After this,you can call methods in Trait and Class by creating instance of Class CalculatorOperation in Singleton Object or in the Main method.
  • 2.
    When a classinherits multiple traits then use extends keyword before the first trait and after that use with keyword before other traits. Syntax- Class Class_Name extends TraitName-1 with TaitName-2 with TraitName-3 { //Body of Class }