I use very often the selfless trait pattern and I need to use "expensive" constants inside the trait: I would like to have a single instance of these values, which might require several steps to be computed, in all my application.
However, the selfless trait pattern results in the following design:
- A trait MyStuff
- An object MyStuff extends MyStuff
Clearly, putting constants inside the object and using them inside a trait creates a cyclic dependency. Putting them on the trait however , makes possible for all the classes extending the trait to override them, and therefore they are certainly not an application-wide singleton.
Is the Scala compiler "clever enough" to makes final vals inside a trait become "old java public static final" ?
What's an example of the cyclic dependency you're concerned about?
Usually that's solved through appropriate use of defs in the trait or lazy vals.
Here's an example issue that is induced by default args (which are synthesized in the companion object).
But if you need eagerness, you can always define early, définition en avance:
If calculating
w
uses members ofFoo
, though, you'd have to go lazy:This is the second time today I've needed the one-question FAQ, but I haven't looked for its new home yet.
(Edit: why, here it is.)