Scala mixin constructor registration invariably

I would like to programmatically bind the values ​​sent to mixins to an instance, and I wonder if there is a more immutable way to do this, and then using a hidden mutable object. First of all, I want to use this for the registry. My current approach is not strictly unchanged after construction, any suggestions?

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)
}

It gives the result I want

val n = new Odd with Even
println(n.values)

Set(5, 1, 6, 9, 2, 7, 3, 8, 4)
+5
source share
1 answer

How about overriding a method? You can then reference the “super” object in the linearization of the attributes,

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)
+3
source

All Articles