Clojure protocol namespaces

March 19, 2014

Key takeaway: When you import a Clojure record, write its namespace with underscores where the source uses dashes.

To use a Clojure protocol from another namespace, :require the protocol and record namespaces and :import the record as a Java class. If the namespace has a dash, it stays a dash in :require and becomes an underscore in :import. I couldn’t find that last part documented anywhere.

This builds on the Drives protocol from Implementing Clojure Protocols:

(ns company.drives)

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

The record’s namespace requires the protocol:

(ns company.school-bus
  (:require [company.drives :refer [Drives]]))

(defrecord SchoolBus [top-speed]
  Drives
  (drive [_ throttle] (str "The wheels on the bus go " (* top-speed throttle))))

The namespace that uses the records requires both namespaces and imports the records:

(ns company.core
  (:require [company.car]
            [company.drives :refer [drive]]
            [company.school-bus])
  (:import company.car.Car
           company.school_bus.SchoolBus))

(defn -main []
  (println (drive (Car. 60.0) 0.4))
  (println (drive (SchoolBus. 45.0) 0.4)))

I got to the underscore by trial and error, from two facts. Java class names can’t have dashes, and Clojure converts dashes to underscores when it compiles to Java. :import is a Java import, so it has to name the record by its Java class name: company.school_bus.SchoolBus.