I have code that has an invariant that the object must be constructed in the function in which it is ultimately used (for various reasons related to the global state, which are not ideal, but are part of the assumption).
eg. Suppose there is a boo function below that is responsible for controlling moo.
def boo(mooGen: () => Moo) { val m = mooGen() // a new MOO must be created HERE m.moo() }
Boo clients who want to use boo must pass type () => Moo, where the function generates the desired Moo.
Ideal customer behavior:
boo( () => new Moo(// specific parameters here) )
Moo is not created until inside the body is boo.
However, the client can easily make a mistake with the following code:
val myMoo = new Moo(// specific parameters here) boo( () => myMoo)
This violates the invariant where we want the moo construct to take place only in boo.
So basically, I want to determine if the return value of mooGen was created in the function call stack or whether it was created in advance.
There are many ways to check this at runtime. However, is there a way to force this pattern at compile time? Using implicits or anything else smart?
Any ideas appreciated!
scala
Pandora lee
source share