Matthew Boston

Implementing Clojure protocols

January 30, 2014

Key takeaway: Think of a Clojure protocol as a Java interface whose functions dispatch on the type of the first argument.

A Clojure protocol is a Java interface whose functions dispatch on the type of their first argument. You define it with defprotocol and implement it with deftype or defrecord.

(defprotocol Drives
  "a protocol for driving"
  (drive [this throttle]))

Every protocol function takes at least one argument, because that first argument is what it dispatches on. Think of it as this.

Implement it with a record:

(defrecord Car [top-speed]
  Drives
  (drive [_ throttle] (str "Spin wheels " (* top-speed throttle))))

The _ is the convention for “I don’t use this value.” Here it’s the Car instance itself.

Call a protocol function like any other Clojure function, with the object first:

(def ferrari (Car. 200.0))
(def honda (Car. 80.0))

(drive ferrari 0.5) ;;=> Spin wheels 100.0
(drive honda 1.0)   ;;=> Spin wheels 80.0

A second record gets its own implementation, and drive dispatches to it:

(defrecord Boat [top-speed]
  Drives
  (drive [_ throttle] (str "Spin propeller " (* top-speed throttle))))

(def chris-craft (Boat. 70.0))

(drive chris-craft 0.8) ;;=> Spin propeller 56.0

A record is still a map underneath, so everything you do with maps works on it:

(:top-speed ferrari) ;;=> 200.0
(def blue-honda (assoc honda :color "blue"))
;;=> Car{:top-speed 80.0, :color "blue"}