Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  ...
}
like image 874
mirelon Avatar asked Oct 19 '22 16:10

mirelon


1 Answers

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)
}
like image 200
codejitsu Avatar answered Oct 22 '22 23:10

codejitsu