SIP 25 will allow a trait to have a constructor. Until that is implemented what would be a good workaround?
Traits does not contain constructor parameters. When a class inherits one trait, then use extends keyword.
Constructors in Scala describe special methods used to initialize objects. When an object of that class needs to be created, it calls the constructor of the class. It can be used to set initial or default values for object attributes.
Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.
In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.
I think the only workaround is to define some abstract methods in the trait that resemble constructor params and override them in concrete implementation:
trait A {
def message:String
}
val a = new A {
override val message = "Hello!"
}
In scala the whole body of your class/trait is the constructor. So basically you use the same approach:
class B (override val message:String) extends A
val b = new B("Hello!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With