5

我想以编程方式将 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)
4

1 回答 1

3

方法覆盖怎么样?然后,您可以在特征线性化中引用“超级”对象,

trait Numbers {
  def holding = Vector[Int]()
  lazy val values = holding
}

trait Odd extends Numbers {
  override def holding = super.holding ++ Vector(1,3,5)
}

trait Even extends Numbers {
  override def holding = super.holding ++ Vector(0,2,4)
}

(new Odd with Even).values // Vector(1, 3, 5, 0, 2, 4)
(new Even with Odd).values // Vector(0, 2, 4, 1, 3, 5)
于 2013-02-05T16:35:28.687 回答