Neil
Neil

Reputation: 8634

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?

Upvotes: 6

Views: 9679

Answers (1)

Aivean
Aivean

Reputation: 10882

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!")

Upvotes: 11

Related Questions