Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala registering mixin constructor results immutably

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)
like image 726
J Pullar Avatar asked Oct 22 '22 18:10

J Pullar


1 Answers

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)
like image 75
Kipton Barros Avatar answered Nov 09 '22 15:11

Kipton Barros