我有一个特征和一个扩展这个特性的类。我可以从以下特点中使用这些方法:
trait A {
def a = ""
}
class B(s: String) extends A {
def b = a
}但是,当我在构造函数中使用该属性的方法时,如下所示:
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)
...
}发布于 2015-03-06 19:10:55
这有点棘手,因为Scala的初始化顺序。我找到的最简单的解决方案是使用apply as factory方法为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)
}https://stackoverflow.com/questions/28904485
复制相似问题