logoalt Hacker News

skybrian11/07/20240 repliesview on HN

Also, you can do lazy initialization in any language that has functions by passing a getter function around instead of a value.

I recently had need for this to implement validation for recursive data structures in TypeScript. It depends on support for forward references in the body of a function. The tricky bit is ensuring that the getter isn’t called until the cycle is completed by defining the forward reference’s target. The type system doesn’t help; you just have to write the implementation so it doesn’t call the getter.