mirelon
mirelon

Reputation: 4996

Using trait method in the class constructor

I have a trait and a class that extends the trait. I can use the methods from the trait as follows:

trait A {
  def a = ""
}

class B(s: String) extends A {
  def b = a 
}

However, when I use the trait's method in the constructor like this:

trait A {
  def a = ""
}

class B(s: String) extends A {
  def this() = this(a) 
}

then the following error appears:

error: not found: value a

Is there some way to define default parameters for the construction of classes in the trait?

EDIT: To clarify the purpose: There is the akka-testkit:

class TestKit(_system: ActorSystem) extends { implicit val system = _system }

And each test looks like this:

class B(_system: ActorSystem) extends TestKit(_system) with A with ... {
  def this() = this(actorSystem)
  ...
}

because I want to create common creation of the ActorSystem in A:

trait A {
  val conf = ...
  def actorSystem = ActorSystem("MySpec", conf)
  ...
}

Upvotes: 4

Views: 322

Answers (1)

codejitsu
codejitsu

Reputation: 3182

It's a little bit tricky because of Scala initialization order. The simplest solution I found is to define a companion object for your class B with apply as factory method:

trait A {
  def a = "aaaa"
}

class B(s: String) {
 println(s)
}

object B extends A {
  def apply() = new B(a)
  def apply(s: String) = new B(s)
}

Upvotes: 2

Related Questions