user5684480
user5684480

Reputation:

Newbie to clojure, trying to understand an expression

I'm new to clojure, can you explain what this means?

(defonce ^:dynamic *some-var1* nil)

I understand the "defonce", but not the rest of the expression. What's "^"? What's "dynamic"? And especially what are "*" in the variable name?

Upvotes: 6

Views: 125

Answers (1)

Dan Prince
Dan Prince

Reputation: 30009

The defonce macro (like many others) allows you to specify some metadata as a first argument. This metadata is often used to give hints to the compiler about the way the symbol is going to be used.

In this case, the ^:dynamic metadata keyword is provided, letting the compiler know that this symbol should be optimized for being dynamically rebound at runtime with the binding form.

The asterisks are just a convention to let other developers know that the symbol is not bound in the regular way. They are there to draw attention to the fact that it might not work in the way you expect it to.

For instance, a binding form is thread local and the symbol is only rebound within the scope of the form.

(defonce ^:dynamic *my-var* false)

(binding [*my-var* true] *my-var*) ;; true

*my-var* ;; false

An attempt to access the value of *my-var* from outside the binding might not return the value that you are expecting.

Because this form has been denoted with the *special-var* convention, we know not to expect the normal behaviour and can read the documentation or study the code before referencing the symbol elsewhere.

Upvotes: 10

Related Questions