我想以编程方式将 mixins 中发送的值绑定到一个实例,我想知道是否有比隐藏的可变对象更不可变的方法来做到这一点。我主要想将它用于注册表。我目前的方法在构建后并不是严格不可变的,有什么建议吗?
trait Numbers {
lazy val values = holding
private var holding = Set.empty[Int]
protected def includes(i:Int) {
holding += i
}
}
trait Odd extends Numbers{
includes(1)
includes(3)
includes(5)
includes(7)
includes(9)
}
trait Even extends Numbers {
includes(2)
includes(4)
includes(6)
includes(8)
}
这给出了我想要的结果
val n = new Odd with Even
println(n.values)
Set(5, 1, 6, 9, 2, 7, 3, 8, 4)