scala – 在类构造函数中使用trait方法
发布时间:2020-12-16 18:36:17 所属栏目:安全 来源:网络整理
导读:我有一个特质和一个扩展特性的类.我可以使用特征中的方法如下: 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() =
|
我有一个特质和一个扩展特性的类.我可以使用特征中的方法如下:
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)
...
}
解决方法
由于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)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
