mir*_*lon 5 constructor scala class traits
我有一个特质和一个扩展特性的类.我可以使用特征中的方法如下:
trait A {
def a = ""
}
class B(s: String) extends A {
def b = a
}
Run Code Online (Sandbox Code Playgroud)
但是,当我在构造函数中使用trait的方法时,如下所示:
trait A {
def a = ""
}
class B(s: String) extends A {
def this() = this(a)
}
Run Code Online (Sandbox Code Playgroud)
然后出现以下错误:
error: not found: value a
Run Code Online (Sandbox Code Playgroud)
有没有办法为特征中的类构造定义默认参数?
编辑:澄清目的:有akka-testkit:
class TestKit(_system: ActorSystem) extends { implicit val system = _system }
Run Code Online (Sandbox Code Playgroud)
每个测试看起来像这样:
class B(_system: ActorSystem) extends TestKit(_system) with A with ... {
def this() = this(actorSystem)
...
}
Run Code Online (Sandbox Code Playgroud)
因为我想在A中创建ActorSystem的通用创建:
trait A {
val conf = ...
def actorSystem = ActorSystem("MySpec", conf)
...
}
Run Code Online (Sandbox Code Playgroud)
由于 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)
}
Run Code Online (Sandbox Code Playgroud)