O'Reilly logo

Web Development with Clojure by Dmitri Sotnikov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required