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 *foo*)
 
 (println *foo*)
 =>#<Unbound Unbound​:​ #​'bar/*foo*>

Here we declare *foo* as a dynamic var and don’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.

 (binding [*foo* ​"I exist!"​]
  (println *foo*))
 =>​"I exist!"

We set *foo* to a string with value “I exist!” inside the binding. When the println function is called within the binding, we no longer get an error when trying to print its value.

This ...

Get Web Development with Clojure, 2nd Edition 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.