Scala | Traits

Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.

Some important points about Scala Traits.

  • Traits are created using trait keywords.
    Syntax:

    trait Trait_Name{
    // Fields..
    // Methods..
    }

    Example:



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Scala program to illustrate how to 
    // create traits
      
    // Trait 
    trait MyTrait
    {
        def pet 
        def pet_color
    }
      
    // MyClass inherits trait
    class MyClass extends MyTrait
    {
          
        // Implementation of methods of MyTrait
        def pet()
        {
            println("Pet: Dog")
        }
          
        def pet_color()
        {
            println("Pet_color: White")
        }
          
        // Class method
        def pet_name()
        {
            println("Pet_name: Dollar")
        }
      
    object Main 
    {
          
        // Main method
        def main(args: Array[String]) 
        {
            val obj = new MyClass();
            obj.pet();
            obj.pet_color();
            obj.pet_name();
        }
    }

    chevron_right

    
    

    Output:

    Pet: Dog
    Pet_color: White
    Pet_name: Dollar
    
  • In Scala, we are allowed to implement the method(only abstract methods) in traits. If a trait contains method implementation, then the class which extends this trait need not implement the method which already implemented in a trait. As shown in the below example.
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Scala program to illustrate the concept of
    // abstract and non-abstract method in Traits
      
    // Trait with abstract and non-abstract methods
    trait MyTrait
    {
        // Abstract method 
        def greeting
      
        // Non-abstract method
        def tutorial
        {
            println("This is a tutorial"
                    "of Traits in Scala")
        }
    }
      
      
    // MyClass inherits trait
    class MyClass extends MyTrait
    {
          
        // Implementation of abstract method
        // No need to implement a non-abstract 
        // method because it already implemented
        def greeting()
        {
            println("Welcome to GeeksfoGeeks")
        }
      
    object Main
    {
          
        // Main method
        def main(args: Array[String]) 
        {
            val obj = new MyClass();
            obj.greeting
            obj.tutorial
        }
    }

    chevron_right

    
    

    Output:

    Welcome to GeeksfoGeeks
    This is a tutorial of Traits in Scala
    
  • Traits does not contain constructor parameters.
  • When a class inherits one trait, then use extends keyword.
    Syntax:

    class Class_Name extends Trait_Name{
    // Code..
    }
  • When a class inherits multiple traits then use extends keyword before the first trait and after that use with keyword before other traits. As shown in the below example.
    Syntax:

    class Class_Name extends Trait_Name1 with Trait_Name2 with Trait_Name3{
    // Code..
    }

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Scala program to illustrate how
    // a class inherits multiple traits
      
    // Trait 1
    trait MyTrait1
    {
          
        // Abstract method 
        def greeting
      
    }
      
    //Trait 2
    trait MyTrait2
    {
          
        // Non-abstract method
        def tutorial
        {
            println("This is a tutorial"
                   "of Traits in Scala")
        }
    }
      
    // MyClass inherits multiple traits
    class MyClass extends MyTrait1 with MyTrait2
    {
          
        // Implementation of abstract method
        def greeting()
        {
            println("Welcome to GeeksfoGeeks")
        }
      
    object Main 
    {
          
        // Main method
        def main(args: Array[String]) 
        {
            val obj = new MyClass();
            obj.greeting
            obj.tutorial
        }
    }

    chevron_right

    
    

    Output:

    Welcome to GeeksfoGeeks
    This is a tutorial of Traits in Scala
    
  • An abstract class can also inherit traits by using extends keyword.
    Syntax:

    abstract class Class_name extends Trait_Name{
    // code..
    }
  • In Scala, one trait can inherit another trait by using a extends keyword.
    Syntax:

    trait Trait_Name1 extends Trait_Name2{
    // Code..
    }
  • Traits support multiple inheritance.
  • In Scala, a class can inherit both normal classes or abstract class and traits by using extends keyword before the class name and with keyword before the trait’s name.
    Syntax:


    class Class_Name1 extends Class_Name2 with Trait_Name{
    // Code..
    } 
  • In Traits, abstract fields are those fields with containing initial value and concrete fields are those fields which contain the initial value. we are allowed to override them in the class which extends trait. If a field is declared using the var keyword, then there is no need to write override keyword when we override them. And if a field is declared using the val keyword, then you must write override keyword when we override them.
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Scala program to illustrate 
    // concrete and abstract fields in traits
      
    trait MyTrait
    {
          
        // Abstract field
        var value: Int 
          
        // Concrete field
        var Height = 10
        val Width = 30
    }
      
    class MyClass extends MyTrait
    {
          
        // Overriding MyTrait's fields
        var value = 12
        Height = 40
        override val Width = 10
          
        // Method to display the fields
        def Display()
        {
            printf("Value:%d", value);
            printf("\nHeight:%d" ,Height);
            printf("\nWidth:%d", Width);
        }
    }
      
    object Main
    {
          
        // Main method
        def main(args: Array[String])
        {
            val obj = new MyClass();
            obj.Display();
        }
    }

    chevron_right

    
    

    Output:

    Value:12
    Height:40
    Width:10
  • We can also add traits to an object instance. Or in other words, We can directly add a trait in the object of a class without inheriting that trait into the class. We can add a trait in the object instance by using with keyword.
    Syntax:

    val object_name = new Class_name with Trait_Name;

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Scala program to illustrate how 
    // to add a trait to an object instance 
      
    class MyClass{}
    trait MyTrait
    {
        println("Welcome to MyTrait");
    }
    object Main 
    {
          
        // Main method
        def main(args: Array[String])
        {
              
            // Here MyTrait is added to the 
            // object instance of MyClass
            val obj = new MyClass with MyTrait;
        }
    }

    chevron_right

    
    

    Output:

    Welcome to MyTrait


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.