I would like to programmatically bind values sent in mixins to an instance, and I am wondering if there is a more immutable way to do this then with a hidden mutable object. Primarily I want to use this for a registry. My current approach isn't strictly immutable 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)
}
This gives the result I want of
val n = new Odd with Even
println(n.values)
Set(5, 1, 6, 9, 2, 7, 3, 8, 4)
How about method overriding? You can then reference the "super" object in trait linearization,
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With