2
votes

I encountered something like this in a program:

(defonce foo nil)
(alter-var-root #'foo (constantly 4))

Since the code above uses constantly, is there any reason to prefer it to a simple def, like below?

(def foo 4)

Is it just to make it more consistent with the defonce, or there are downsides to using def?

1

1 Answers

1
votes
(ns banana)
(defonce foo nil)

(ns user)
(use 'banana)

foo ;=> nil

(alter-var-root #'foo (constantly 42))
foo ;=> 42

(def foo 50)
CompilerException java.lang.IllegalStateException: foo already refers to: #'banana/foo in namespace: user