Clojure vars with metadata

Is it possible to create a new var with metadata without going through the "intermediate" var?

In other words, I know that I can do the following:

(def a-var 2) (def another-var (with-meta a-var {:foo :bar})) 

but is there a way to create another-var without first creating a-var ?

+7
clojure metadata
source share
2 answers

Like this:

 user> (def ^{:foo :bar} another-var 2) #'user/another-var user> (clojure.pprint/pprint (meta #'another-var)) {:ns #<Namespace user>, :name another-var, :file "NO_SOURCE_FILE", :line 1, :foo :bar} nil 
+6
source share

Also note that (def another-var (with-meta a-var {:foo :bar})) does not bind metadata to Var, but to the value. And since your a-var example contains an integer, I would not expect your example to work at all, since integers cannot contain metadata.

 user=> (def a-var 2) #'user/a-var user=> (def another-var (with-meta a-var {:foo :bar})) java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IObj (NO_SOURCE_FILE:2) 
+6
source share

All Articles