Scala Trait

Reading Time: 2 minutes

Introduction:

Scala trait is like an interface with partial implementation. Scala trait is a collection of abstract and non-abstract methods. You can create traits that have all abstract methods or some abstract methods and some non-abstract methods.

Any variable declare using the val or var keyword in a trait gets implement internally in the class that implements the trait. A variable declared with val or var but not initialized is considere abstract.

Implementations of traits are compile into Java interfaces with corresponding implementation classes that hold the methods implemented in the traits.

Example :

trait MyTrait
{
    def mobile  
    def mobile_color
}

class MyClass extends MyTrait
{
      
    // Implementation of methods of MyTrait

    def mobile()
    {
        println("mobile: Iphone")
    }
      
    def mobile_color()
    {
        println("mobile_color: White")
    }
      
    // Class method

    def mobileInternalMemory()
    {
        println("Internal Memory: 8Gb")
    }
} 
  
object Main 
{
      
    // Main method
    def main(args: Array[String]) 
    {
        val obj = new MyClass();
        obj.mobile();
        obj.mobile_color();
        obj.mobileInternalMemory();
    }
}

Output:

mobile: Iphone
mobile_color: White
Internal Memory: 8Gb

Scala Trait having abstract and non-abstract methods:

You can define methods in traits as you can in abstract classes. In Scala, a trait is almost like an abstract class except that it does not have a constructor. You cannot extend multiple abstract classes but you can extend multiple traits.

Example:

trait animal{  
    def legs()         // Abstract method  
    def colure(){         // Non-abstract method  
        println("Colure: Black")  
    }  
}  
  
class Dog extends animal{  
    def legs(){  
        println("Legs: Four")  
    }  
}  
  
object MainObject{  
    def main(args:Array[String]){  
        var a = new Dog()  
        a.legs()  
        a.colure()  
    }  
}  

Output:

Legs: Four
Colure: Black

When to Use Traits?

There is no firm rule, but here are few guidelines to consider.

  1. In this case, create a concrete class instead of reusing the behavior. After all, it is not reusable behavior.
  2. Only traits can be mixed into different parts of the class hierarchy if they can be reused in multiple, unrelated classes.
  3. If efficiency is very important, lean towards using a class.

Reference:

https://www.javatpoint.com/scala-trait

Conclusion:

This topic will be use in plenty of useful places in your application. Don’t put the entire code in every place rather define the above method and use it everywhere. Make it a practice for all exceptions which a small of code may throw at runtime. Also, try to include a possible course of action, the user should follow in case these exceptions occur.

 If you found anything missing or you do not relate to my view on any point, drop me a comment. I will be happy to discuss. For more blogs, click here

Written by 

Shubham Shrivastava is a Software intern at Knoldus Inc. in Noida. He did his B.Tech from Dr. A.P.J. Abdul Kalam Technical University. He is familiar with Scala, Python, Unit testing, Git. He is currently working in the Scala Practice area. He loves to dig deep in coding and loves to play Cricket.