Suppose we have
scala> trait A { val y: Int; val x = 1; val y2 = y + 1 }
scala> trait B { val y: Int = 1; val x: Int; val x2 = x + 1 }
scala> class C extends A with B
Then both y2
and x2
should end up with value 2 in C
. Now if we mixin A
then B
then y2
has value 1 since the value of y
is the default 0. Similarly x2
will have value 1 if we mixin B
then A
. Furthermore if these things where Objects rather than Ints then we could end up with a NullPointerException
.
What I want, in an ideal world, is the initialisation to NOT be lazy, but the order of initialisation to be automagically implied by the dependency graph of the values. I.e. a way of telling the compiler to reshuffle initialisation order rather than using default values. Moreover I do NOT want to refactor the traits into smaller traits and then work out the correct mixin order myself (in a huge project when sometimes I have to mixin 5 traits, this is painful to work out).
UPDATE: To put it another way ... when we mixin traits we imagine overlaying the traits on top of each other, but it doesn't really work like this when it comes to vals ... how to make it work like this
UPDATE: If it really isn't possible, I'd be happy if someone could share a link to any already existing feature request tickets for typesafe along the lines of adding a keyword to scala called "overlay" which could be used along the lines of:
scala> class C overlay A overlay B
You can't. Traits are initialized in the order they're given and that's what it has to be - anything else would be impossible to reason about, it's more important that the initialization order is predictable than that it is optimal. Your only choices are to use lazy (or to use def rather than val), or not to use traits for this.