I was reading the section on Lazyness [sic] over at Twitter's Effective Scala page, which includes this suggestion (emphasis is mine):
Use lazy fields for this purpose [computing and caching values on-demand], but avoid using lazyness when lazyness is required by semantics. In these cases it's better to be explicit since it makes the cost model explicit, and side effects can be controlled more precisely.
I don't understand why they would make this claim. Why would it be better to avoid using the lazy
keyword for cases when laziness is required by the semantics (meaning that it's necessary for correctness in your program rather than just using it as an optimization). I don't see how writing your own lazy initialization code would make the fact that laziness is required more clear than using the lazy
keyword built into the language! I know there's a bit of extra overhead involved with making lazy
fields thread-safe, but I don't think that's what they're getting at here...
Is there some hidden merit to this guideline on the use of lazy
that I'm totally missing, or am I better off just ignoring this suggestion?
lazy
keyword to postpone a side effect, you're probably doing it wrong. And sometimes, when some computation is really long, that should count as side effect too (the effect being a quantifiable pause). – Upend