O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type Hinting for Performance

You may have noticed some code examples that use syntax referring to Java class names, such as ^String here:

(defn length-of
  [^String text]
  (.length text))

The ^ClassName syntax defines a type hint, an explicit indication to the Clojure compiler of the object type of an expression, var value, or a named binding.

The typical type hint syntax is expanded by the Clojure reader into metadata on the value following the hint. So, the ^String text hinted binding form is expanded by the reader into the equivalent expression ^{:tag String} text, which evaluates to the symbol text with the metadata {:tag String}. Clojure internally uses the term “tag” for type.

These hints are used by the compiler only to avoid emitting reflective interop calls; otherwise, they are unnecessary. So, if our code does not include an interop call, there is no need to include a type hint:

(defn silly-function
  [v]
  (nil? v))

Any hint you provide for v here would simply be left unused.

Warning

Type hints on function arguments or returns are not signature declarations: they do not affect the types that a function can accept or return. Their only effect is to allow Clojure to call Java methods and access Java fields using compile-time generated code—rather than the much-slower option of using reflection at runtime to search for methods or fields matching the interop form in question. Thus, if a hint doesn’t inform an interop operation, they are effectively no-ops. For example, this function hints ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required