type is a Clojure function for identifying an object’s type. It first consults the object’s :type metadata tag; when no tag is present, it reports the underlying class. section 15.2
Use type to distinguish values, inspect runtime representations, or select behavior:
- A metadata tag can override the underlying class: a vector tagged with {:type "MyVector"} returns "MyVector" from type, while class still returns clojure.lang.PersistentVector. section 15.2
- type supports simple type-based polymorphism, including dispatch on keywords such as :person and :business or on String. section 15.2
- For extensible dispatch, combine type with defmulti and defmethod so new type cases can be added incrementally. section 15.2
Dispatching on tagged contacts
Define tagged values with (vary-meta obj assoc :type t), then dispatch with (defmulti print-contact type). A tagged person prints "Mr John", a tagged business prints "Manning (Marjan)", a String prints "Contact: Mr. Renzo", and nil uses the default case. section 15.2
(class []) ; #1
;; clojure.lang.PersistentVector
(class "") ; #2
;; java.lang.String
(class #()) ; #3
;; user$eval25$fn__26
(class nil) ; #4
;; nil
(type {:a 1}) ; #5
;; clojure.lang.PersistentArrayMap
(type (with-meta {:a 1} {:type :custom})) ; #6
;; :custom
Compare type results for an empty vector, String, function, nil, an ordinary map, and a map carrying a custom :type tag. section 15.0
