In Scala, declaring a
lazy means that its value won't be evaluated until it's used for the first time. This is often explained/demonstrated as being useful for optimization, in case a value might be expensive to compute but not needed at all.
It's also possible to use
lazy in a way that it's necessary for the code to work correctly, rather than just for efficiency. For example, consider a
lazy val like this:
lazy val foo = someObject.getList().find(pred) // don't use this until after someObject filled its list!
foo weren't lazy, then it would always contain
None, since its value would be evaluated immediately, before the list contained anything. Since it is lazy, it contains the right thing as long as it isn't evaluated before the list is filled.
My question: is it considered okay to use
lazy in places like this where its absence would make the code incorrect, or should it be reserved for optimization only?
(Here is the real-world code snippet that inspired this question.)