Clojure - Vars
Vars
Vars are associations between symbols and objects. They can also be used in tackling concurrency tasks. We can dynamically bind them and alter their roots.
Dynamic Binding
Dynamic vars van be useful for creating a global name that should refer to different values in different contexts.
Creating and Binding Dynamic Vars
1(def ^:dynamic *email-address* "[email protected]")
2
3(println *email-address*)
4; => [email protected]
5
6(binding [*email-address* "[email protected]"]
7 *email-address*)
8; => [email protected]
Dynamic Var Uses
Dynamic vars are most often used to name a resource that one or more functions target. For example
Clojure comes with built-in dynamic vars like *out* which represent the standard output for
print operations.
1(binding [*out* (clojure.java.io/writer "print-output")]
2 (println "Hello, World!"))
3
4(slurp "print-output")
5; => Hello, World!
Dynamic vars are most often used to set configuration values.
Altering the Var Root
You can also change the root (underlying value) of the var. For example:
1(def hello "Hello")
2hello
3; => "Hello"
4
5(alter-var-root #'hello (fn [_] "HELLO"))
6hello
7; => "HELLO"
This is rarely done because it goes against functional programming philosophy of immutability.