liveBook · Manning

Deftype

As explained in Clojure: The Essential Reference

deftype is a Clojure construct that declares a concrete type and generates a corresponding Java class with fields and method implementations.

deftype declares a concrete Clojure type backed by a generated Java class. It names fields, implements interfaces, and supplies method bodies, making it a low-level bridge to Java-style objects and polymorphism. section 15.0 section 15.4

A definition can include:

  • Fields such as x and y, normally public and final. section 15.4
  • Interface implementations with methods matching the declared contracts; java.lang.Object is the only accepted class. section 15.4
  • Mutable fields marked ^:unsynchronized-mutable or ^:volatile-mutable; mutable access requires explicit synchronization during concurrent use. section 15.4
  • Generated classes suitable for ahead-of-time compilation and use by Java applications. section 15.4

Comparable point type

(deftype Point [x y] Object (toString [this] (format "[%s,%s]" x y)) Comparable (compareTo [p1 p2] (compare (distance (.x p1) (.y p1) 0 0) (distance (.x p2) (.y p2) 0 0)))) (sort [(->Point 5 2) (->Point 2 4) (->Point 3 1)]) ;; points ordered as [3,1], [2,4], [5,2] section 15.4

(deftype Point [x y]) ; #1

(def p (new Point 1 2)) ; #2
(def p (Point. 1 2))
(def p (->Point 1 2))

(.x p) ; #3
;; 1
(.-x p)
;; 1
(. p y)
;; 2

Construct a Point with new, constructor syntax, or the generated ->Point function, then access fields through Java interop. section 15.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains declarations, construction, method implementation, field mutability, synchronization, and AOT compilation.
Examples
Uses Point sorting, custom toString output, mutable Person properties, and compiled Java-accessible classes.
What it assumes
Assumes familiarity with Clojure syntax and Java-style interfaces, while demonstrating construction and field access directly.
What you can do after
Build concrete Java-compatible Clojure objects, implement interfaces, expose fields, and control selected field mutability.
How it connects
Connects deftype with Java interfaces, gen-class, defrecord, defprotocol, definterface, and AOT compilation.

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.