我有一个庞大的类(class),我想在其中加入许多特征。我类的每个部分都有一组其他部分未使用的值。这些参数是从属性文件中读取的,有时会进行一些计算。我想让每个特征负责初始化自己的变量。我希望这些值对特性是私有(private)的。不幸的是,特征没有构造函数(这是我真正想要的)。
创建混合一组特征的对象的模式是什么,其中特征具有需要初始化的值?
这是一个例子:
class Foo( properties: Properties ) extends Bar with Baz
trait Bar {
private val something
}
trait Baz {
private val somethingElse
}
我如何初始化 Bar.something 和 Baz.somethingElse 而不是使它们抽象和非私有(private),或者添加 init() 方法并使它们成为 vars?
谢谢 彼得
最佳答案
早期初始化怎么样?
trait A {
val f: String
val a = "I would have used " + f
}
trait B {
val f: String
val b = "I would have used " + f + " too!"
}
class C extends { val f = "the string" } with A with B
如果你把它放到一个 REPL 中:
scala> List(c.a, c.b).map(println _)
I would have used the string
I would have used the string too!
关于scala - 在 Traits 中初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28076228/