在类构造函数中使用trait方法

时间:2015-03-06 17:40:21

标签: scala class constructor traits

我有一个特质和一个扩展特性的类。我可以使用特征中的方法如下:

trait A {
  def a = ""
}

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

但是,当我在构造函数中使用trait的方法时:

trait A {
  def a = ""
}

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

然后出现以下错误:

error: not found: value a

是否有某种方法可以为特征中的类构造定义默认参数?

编辑:澄清目的:有akka-testkit:

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

每个测试都是这样的:

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

因为我想在A:

中创建ActorSystem的通用创建
trait A {
  val conf = ...
  def actorSystem = ActorSystem("MySpec", conf)
  ...
}

1 个答案:

答案 0 :(得分:3)

由于Scala初始化顺序,这有点棘手。我找到的最简单的解决方案是使用 apply 作为工厂方法为您的B类定义一个伴随对象:

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)
}