Dynamic Variables

Clojure provides support for declaring dynamic variables that can have their value changed within a particular scope. Let’s look at how this works.

 
(​declare​ ^{:dynamic true} *foo*)
 
(​println​ *foo*)
 
=>#<Unbound Unbound: #'bar/*foo*>

Here we declared *foo* as a dynamic Var and didn’t provide any value for it. When we try to print *foo* we get an error indicating that this Var has not been bound to any value.

Let’s look at how we can assign a value to *foo* using a binding.

 
(​defn​ with-foo [f]
 
(​binding​ [*foo* ​"foo"​]
 
(f)))
 
(with-foo #(​println​ *foo*))
 
=>foo

We set *foo* to a string with value "foo" inside our with-foo function. When our anonymous function is called inside with-foo we no longer get an error ...

Get Web Development with Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.