Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

providing a constructor for a scala trait

SIP 25 will allow a trait to have a constructor. Until that is implemented what would be a good workaround?

like image 455
Neil Avatar asked Apr 29 '16 23:04

Neil


People also ask

Can a Scala trait have a constructor?

Traits does not contain constructor parameters. When a class inherits one trait, then use extends keyword.

Can Scala object have constructor?

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.

What is a Scala constructor?

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.

How do I create a class constructor in Scala?

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.


1 Answers

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!")
like image 92
Aivean Avatar answered Oct 01 '22 05:10

Aivean