philipbohun.com

Glojure by Example: Protocols

A protocol is a set of functions dispatched on the type of the first argument. It plays the role of a small Go interface. extend-type supplies the implementation.

(defprotocol Summarize
  (summarize [this]))

(defrecord Book [title pages])

(extend-type Book
  Summarize
  (summarize [book]
    (str (:title book) " (" (:pages book) " pages)")))

The same protocol can be extended to a host type such as String. Inline implementations inside defrecord, and reify, are not supported in this version of Glojure, so extend-type is the form to use.

(extend-type String
  Summarize
  (summarize [s] s))

(println (summarize (->Book "Persuasion" 249)))
(println (summarize "note"))

The function dispatches on the runtime type of its argument.

$ glj protocols.glj
Persuasion (249 pages)
note

Next example: Multimethods.