Clojure Metadata

Clojure has a feature called Metadata i.e. data about data. Using metadata it is possible to add a map with some information to some objects like symbols and collections.


The API for metadata is pretty basic-

with-meta - Set the metadata map. The reader macro ^ can also be used instead of the meta function. Multiple ^ macros can be cascaded.

(def foo ^{:my-meta "bar"} {:lang "clojure"})
;; #'user/foo

(def foo2 ^{:my-meta "bar"} ^{:more-meta "baz"} {:lang "lisp"})
;; #'user/foo2

meta - Get the metadata map set for the object or nil

(meta foo)
;; {:my-meta "bar"}

(meta foo2)
;; {:more-meta "baz", :my-meta "bar"}

Internal usage

Clojure source uses metadata for annotating various artifacts. Some keys are :doc, :added (equivalent to javadoc @since), :static, :dynamic, :arglists.


The java interfaces that declare metadata support are IMeta and IObj.

package clojure.lang;

interface IMeta {
  IPersistentMap meta();

interface IObj extends IMeta {
  IObj withMeta(IPersistentMap meta);

with-meta invokes withMeta with the map object and meta returns the map.

IObj is a super interface for multiple clojure types.