Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Macros and Protocols

Multimethods and Polymorphism

Learn Clojure multimethods: defmulti and defmethod, dispatch on any value, :default, derive and isa? hierarchies, prefer-method, and how they compare to protocols.

A protocol chooses an implementation from the type of the first argument. Sometimes that is too narrow: you may want to choose by a key in a map, by the types of two arguments, by a value or by a category in a hierarchy. Multimethods handle all of these. A multimethod has two parts: a dispatch function that turns the arguments into a dispatch value, and any number of methods, one per dispatch value.

defmulti and defmethod

CLOJURE
(defmulti area :shape)    ; dispatch function: the :shape key

(defmethod area :circle [{:keys [r]}]
  (* Math/PI r r))

(defmethod area :rect [{:keys [w h]}]
  (* w h))

(defmethod area :default [shape]
  (throw (ex-info "Unknown shape" {:shape shape})))

(area {:shape :rect :w 3 :h 4})   ;=> 12
(area {:shape :circle :r 1})      ;=> 3.141592653589793
(area {:shape :hex})              ; throws ex-info "Unknown shape"

When (area x) is called, Clojure computes (:shape x), finds the method registered for that value, and calls it with the original arguments. The :default dispatch value handles everything that matches no other method. Without it, an unmatched value throws IllegalArgumentException: No method in multimethod 'area' for dispatch value.

Because the dispatch function can be anything, you are free to dispatch on structure:

CLOJURE
;; dispatch on the types of two arguments
(defmulti combine (fn [a b] [(class a) (class b)]))

(defmethod combine [String String] [a b] (str a b))
(defmethod combine [Number Number] [a b] (+ a b))
(defmethod combine [String Number] [a b] (str a (apply str (repeat b "!"))))

(combine "hi" "!")   ;=> "hi!"
(combine 1 2)        ;=> 3
(combine "wow" 3)    ;=> "wow!!!"

Method signatures can destructure like any function. Methods can be added later from other namespaces and files, which is how libraries let you extend their behavior (the "open for extension" property protocols also have).

Dispatch on a value for state machines and tags

A common use is processing different message or event types:

CLOJURE
(defmulti handle-event :type)

(defmethod handle-event :user/created [{:keys [name]}]
  (println "welcome" name))

(defmethod handle-event :user/deleted [{:keys [id]}]
  (println "bye user" id))

(handle-event {:type :user/created :name "Ana"})   ; prints: welcome Ana

Namespaced keywords like :user/created avoid collisions between libraries.

Hierarchies: derive and isa?

Dispatch values can be related in hierarchies. derive declares that one keyword (or class) "is a" another. A method for a parent value then applies to its children unless a more specific method exists.

CLOJURE
(derive ::square ::rect)
(derive ::rect   ::shape)
(derive ::circle ::shape)

(isa? ::square ::shape)   ;=> true
(parents ::square)        ;=> #{:user/rect}
(ancestors ::square)      ;=> #{:user/rect :user/shape}

(defmulti sides identity)
(defmethod sides ::shape  [_] :unknown)
(defmethod sides ::rect   [_] 4)

(sides ::square)   ;=> 4   ; nearest ancestor wins: ::rect, not ::shape
(sides ::circle)   ;=> :unknown

Double-colon keywords such as ::rect expand to the current namespace (:user/rect at the REPL). Java class inheritance is also honored, so a method for Number applies to Long and Double.

Hierarchies can be changed at runtime with derive and underive, which is useful for plugin-like systems where a rule says "admin is-a user".

Resolving ambiguity

If a value matches two methods that are unrelated (diamond inheritance), Clojure throws "Multiple methods match dispatch value". Use prefer-method to say which one wins:

CLOJURE
(derive ::a ::p1)
(derive ::a ::p2)
(defmulti who identity)
(defmethod who ::p1 [_] "p1")
(defmethod who ::p2 [_] "p2")
(prefer-method who ::p1 ::p2)
(who ::a)   ;=> "p1"

Inspecting and changing multimethods

CLOJURE
(methods area)             ; map of dispatch value -> function
(get-method area :rect)    ; the function itself
(remove-method area :rect)
(ns-unmap *ns* 'area)      ; needed to REDEFINE the defmulti itself

A frequent REPL gotcha: defmulti only defines the multimethod once. If you change the dispatch function and re-evaluate defmulti, nothing happens, because the var already exists. Use (def area nil) first, or the more precise ns-unmap, then evaluate defmulti again. Methods, on the other hand, are replaced simply by evaluating defmethod again.

Protocol or multimethod?

Protocol Multimethod
Dispatch type of first argument any function of all arguments
Speed fast (JVM interface dispatch) slower (function call plus lookup, cached)
Hierarchies Java types only custom hierarchies via derive
Open to extension yes yes

Choose a protocol for type-based behavior in a performance-sensitive abstraction, and a multimethod when you dispatch on data (such as a :type key from JSON), on multiple arguments, or on a custom hierarchy. Many applications get by with plain case or cond on a keyword; reach for polymorphism when you expect others to add cases.

Try it: a multimethod in JavaScript

This stand-in builds defmulti/defmethod/derive with a dispatch function, a method table and a hierarchy lookup that walks up to ancestors.

JS defmulti with a hierarchy

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

No output.

Try it: dispatch on two arguments

JS Dispatch on a pair of types

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. In (defmulti area :shape), what is :shape?

    The keyword acts as a function that extracts the dispatch value from the argument.
  2. 2. What happens if no method matches and there is no :default?

    Clojure throws 'No method in multimethod ... for dispatch value'. Add a :default method to handle the rest.
  3. 3. What does (derive ::square ::rect) enable?

    isa? relationships let dispatch fall back to ancestors, with the nearest matching ancestor winning.
  4. 4. Why does re-evaluating a changed defmulti seem to do nothing?

    defmulti does nothing if the var is already bound. Remove it first with ns-unmap or (def name nil).

Summary

  • A multimethod pairs a dispatch function (defmulti) with methods per dispatch value (defmethod), plus an optional :default.
  • Dispatch can use any function of the arguments: keys, types of several arguments or computed values.
  • derive, isa? and prefer-method build and resolve hierarchies.
  • Redefine a defmulti by removing the var first; defmethod replaces methods directly.
  • Use protocols for fast type-based dispatch; multimethods for data-driven or multi-argument dispatch.

Next: Leiningen and deps.edn