Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Macros and Protocols

Protocols and Records

Learn polymorphism in Clojure with protocols and records: defprotocol, defrecord, extend-protocol, extend-type, reify, deftype and when to use maps instead.

Clojure favors plain data (maps, vectors) and functions over classes. But sometimes you want polymorphism: one operation, with different behavior depending on the type of the first argument. The language offers two mechanisms for this. Protocols (this lesson) dispatch on the type of the first argument and are fast, like Java interfaces. Multimethods dispatch on any function of the arguments and are more flexible.

defprotocol

A protocol is a named set of function signatures with optional docstrings.

CLOJURE
(defprotocol Shape
  "Something with an area and a name."
  (area [this] "Returns the area.")
  (describe [this] [this prefix] "Describes the shape."))

This defines the functions area and describe (with two arities). Each function's first parameter is the object being dispatched on (conventionally this). Nothing is implemented yet: the protocol only declares the contract.

defrecord

A record is like a map with a fixed set of named fields and a type of its own. It can implement protocols inline.

CLOJURE
(defrecord Circle [r]
  Shape
  (area [_] (* Math/PI r r))
  (describe [this] (describe this "circle"))
  (describe [this prefix] (str prefix " of radius " r)))

(defrecord Rect [w h]
  Shape
  (area [_] (* w h))
  (describe [this] (describe this "rectangle"))
  (describe [this prefix] (str prefix " " w "x" h)))

(def c (->Circle 2))
(def r (map->Rect {:w 3 :h 4}))

(area r)         ;=> 12
(describe r)     ;=> "rectangle 3x4"
(:w r)           ;=> 3
(assoc r :h 10)  ;=> #user.Rect{:w 3, :h 10}

Constructors are generated for you: positional ->Rect and map-based map->Rect. Fields inside method bodies are available as local names, as r, w and h above.

Records behave like maps: you can use :w, get, assoc, dissoc, keys and destructuring, and they are immutable. Two records are equal if they have the same type and field values. Records can also hold extra keys not in the field list (these are stored in an extension map), but dissociating a declared field returns a plain map. Compared to ordinary maps, records are faster for field access, and they dispatch on their type.

Extending types you do not own

Protocols are open: you can implement a protocol for an existing type, including Java classes, without modifying them. This avoids the "expression problem" of classes.

CLOJURE
(extend-protocol Shape
  nil
  (area [_] 0)
  (describe [_] "nothing")

  String
  (area [s] (count s))
  (describe [s] (str "text: " s)))

(area "abcd")   ;=> 4
(area nil)      ;=> 0

extend-protocol lists many types for one protocol; extend-type lists many protocols for one type. You can even extend Object for a default implementation. This is the standard way to adapt library types to your own abstractions.

reify and deftype

reify creates a one-off anonymous object implementing protocols (or Java interfaces), capturing local variables like a closure. It is useful for adapters and tests.

CLOJURE
(let [side 5]
  (area
    (reify Shape
      (area [_] (* side side))
      (describe [_] "a square"))))
;=> 25

deftype defines a type with fields and methods but no map behavior. It is aimed at performance-sensitive code and at building new data structures, and it supports mutable fields (^:volatile-mutable) for implementation details. In everyday application code, prefer records.

Protocols versus other options

You need... Use
Behavior that depends on the type of the first argument, with speed protocol
Dispatch on a value, several arguments or a custom rule multimethod
Structured data with a few named fields plain map (often enough) or record
An anonymous implementation reify

Protocol functions are ordinary functions that you can pass to map, and (satisfies? Shape x) tells you whether x implements a protocol (slow, avoid in hot code), while (instance? Circle x) tests a record type directly.

Common pitfalls:

  • Overusing records. Start with maps and keyword-based functions; introduce records when you need polymorphism or measured speed.
  • Redefining a protocol at the REPL leaves old records implementing the old version. Reload the records after redefining.
  • Dispatching on non-first arguments: protocols cannot; use a multimethod.
  • Implementing the same method for a type twice (via inline and extend) leads to confusion; choose one.

Try it: polymorphism by type in JavaScript

JavaScript classes model records implementing a protocol, and a Map keyed by constructor models extend-protocol on types we do not own.

JS A Shape protocol

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: records are values

Records are immutable and compare by value; this stand-in mimics assoc, equality and map-like access.

JS Immutable record behavior

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a protocol dispatch on?

    Protocols dispatch on the type of the first argument. For other rules, use multimethods.
  2. 2. How can you make an existing Java class satisfy your protocol?

    Protocols are open: extend-protocol and extend-type add implementations to types you do not own.
  3. 3. Which statement about records is true?

    Records support map operations and are immutable, with positional ->Type and map->Type constructors.
  4. 4. What is reify used for?

    reify returns a one-off instance, ideal for adapters and test doubles.

Summary

  • defprotocol declares functions that dispatch on the type of the first argument.
  • defrecord gives you map-like, immutable typed data that can implement protocols inline.
  • extend-protocol/extend-type add behavior to existing types; reify makes anonymous implementations; deftype is for low-level data structures.
  • Start with maps; use records and protocols when you need type-based polymorphism.

Next: Multimethods and Polymorphism