I'm trying to find the idiomatic way to defer the initialization of a var (which I really intend to be immutable).
(def foo nil)
...
(defn init []
; (def foo (some-function))
; (set! foo (some-function)))
I know Rich Hickey said re-defing isn't idiomatic. Is set!
appropriate here?
I would use delay
:
Takes a body of expressions and yields a Delay object that will invoke the body only the first time it is forced (with force or deref/@), and will cache the result and return it on all subsequent force calls. See also - realized?
Example usage:
(def foo (delay (init-foo))) ;; init-foo is not called until foo is deref'ed
(defn do-something []
(let [f @foo] ;; init-foo is called the first time this line is executed,
;; and the result saved and re-used for each subsequent call.
...
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With