Traits

    A trait encapsulates methods and attributes into a single unit. The main purpose of the creation of traits is to enhance reusability by using inheritance.

    As we already discussed while doing inheritance, we can extend only a single class, but unlike classes, we can mix in any number of traits.

    Suppose you are familiar with Java . You can understand traits as a combination of abstract classes and interfaces.

    A trait can be created by using a keyword trait. Object creation for a trait is impossible until it is extended by a class where it can be defined completely.

    Example:

    trait Phone {
     val modelNumber: Long
     def call(): String
    }
    
    class SamsungPhone extends Phone {
     override val modelNumber = 12345L
     override def call(): String = "I am calling from Samsung phone"
     def clickPhotos() = "I am capable of clicking pictures also"
    }
    
    class OnePlusPhone extends Phone {
     override val modelNumber = 2345L
     override def call() = "I can click HD pics"
    }
    
    val onePlus7pro = new OnePlusPhone
    onePlus7pro.call()
    onePlus7pro.modelNumber

    This feature is available in some languages to extend multiple classes in a single class. But this feature is not available in Scala. That's why we needed a trait.

    Syntax to extend:

    Class A extend ClassB with TraitC with TraitD