liveBook · Manning

Type

As explained in Clojure: The Essential Reference

type is a Clojure function that returns an object's type, consulting a :type metadata tag before determining the underlying class.

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

How Clojure: The Essential Reference covers it

How deep it goes
Explains metadata precedence, contrasts type with class, and demonstrates conditional and multimethod dispatch.
Examples
Demonstrates vectors, strings, functions, nil, metadata-tagged maps, contact dispatch, and instance? checks.
What you can do after
Evaluate/understand runtime types and apply type via defmulti for metadata-driven dispatch.
How it connects
Connects type with class, instance?, metadata, multimethods, and protocols.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.