liveBook · Manning

Multimethod

As explained in Clojure: The Essential Reference

A multimethod is a Clojure polymorphic function whose implementation is selected by applying a dispatch function to its arguments.

A multimethod is a polymorphic Clojure function whose implementation is selected by applying a user-supplied dispatch function to its arguments. Unlike protocols, it can dispatch on arbitrary values, use custom derivation hierarchies, and gain methods without registering new types. section 15.11 section 15.12

Dispatching a data-driven calculator

Define `calculate` to dispatch on `:op`, then attach implementations with `defmethod`. A `nil` method evaluates leaf pairs, while `:default` reports unsupported expressions. A custom hierarchy can group operations by arity, allowing shared implementations for variable-, one-, and two-argument operations. Evaluating the payment expression produces `205659.10262863498`. section 15.11

Manage multimethod behavior explicitly:

  • Extend a declared multimethod at runtime with additional `defmethod` definitions, without registering a new type. section 15.11
  • Remove implementations with `remove-method` or inspect registered implementations with `methods`. section 15.11
  • Resolve overlapping dispatch matches with `prefer-method`; otherwise, ambiguous methods raise an exception. section 15.11
  • Provide a `:default` method to handle unmatched values or throw a targeted exception. section 15.11

How Clojure: The Essential Reference covers it

How deep it goes
Explains declaration, method extension, custom hierarchies, removal, inspection, precedence, defaults, and dispatch failures.
Examples
Uses a data-driven calculator, runtime operator extension, temperature-based sound speed, collection dispatch, and recursive methods.
What you can do after
Build it from scratch, extend implementations, inspect dispatch state, resolve ambiguities, and diagnose unmatched or conflicting methods.
How it connects
Connects multimethods with protocols, dispatch functions, custom hierarchies, defmulti, defmethod, and method precedence.

Also explained in

Compare how 2 books explain multimethod →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.