4

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)
  ...
}
1
  • I don't see how you can have a constructor parameter that depends on a class member. The class member could (and usually does?) depend on the constructor parameters, which would allow for circular referencing. So def a isn't yet initialized. Commented Mar 6, 2015 at 20:22

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, but the problem is, that B is called like new B() (it's in a generated code so I cannot modify it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.