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
