liveBook · Manning

Definterface

As explained in Clojure: The Essential Reference

definterface is a Clojure macro that declares a Java interface without providing protocol dispatch semantics.

definterface is a Clojure macro for declaring a Java interface: it specifies method names and arities, but supplies no implementations or protocol-style dynamic dispatch. Implementations can be attached to a deftype. section 15.0 section 15.4

Use definterface when an explicit Java-facing contract is needed:

  • Declare interface methods with signatures such as (getName []) or (setAge [n]). section 15.4
  • Implement the declared methods in a deftype, where method bodies directly access fields or perform updates. section 15.4
  • Choose defprotocol instead when the goal is Clojure-oriented dynamic dispatch independent of Java interface calls. section 15.0

A mutable Person implementation

(definterface IPerson (getName []) (setName [s]) (getAge []) (setAge [n])) (deftype Person [^:unsynchronized-mutable name ^:unsynchronized-mutable age] IPerson (getName [this] name) (setName [this s] (set! name s)) (getAge [this] age) (setAge [this n] (set! age n))) (def p (->Person "Natasha" "823")) (.getAge p) ; "823" (.setAge p 23) ; 23 section 15.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains declaration and implementation through deftype, but stops short of protocol dispatch semantics.
Examples
Uses an IPerson contract implemented by a mutable Person deftype with getter and setter calls.
What you can do after
Apply it via deftype to expose Clojure-created objects through explicit Java interface methods.
How it connects
Connects Java interfaces with deftype, gen-interface, gen-class, defprotocol, proxy, and reify.

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.