Dynamic Variables

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (77 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Namespaces | TOC | Polymorphism 👉

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 hasn’t 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 technique can be useful when dealing with resources such as file streams, database connections, or scoped variables. In general, the use of dynamic variables is discouraged since they make code more opaque and difficult to reason about. However, they have legitimate uses, and it’s worth knowing how they work.

👈 Namespaces | TOC | Polymorphism 👉

Web Development with Clojure, Third Edition by Dmitri Sotnikov, Scot Brown can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.