Clojure Medium · Lesson 1 · On the house

Multimethods

defmulti dispatch functions, defmethod, :default, and hierarchies. Lesson 1 is free — on the house.

Lessons · Clojure Medium · Lesson 1 of 10 · On the house

Multimethods

defmulti dispatch functions, defmethod, :default, and hierarchies.

Illustration for Clojure
Lesson 1 is on the house.

A multimethod picks an implementation from any function of its arguments: (defmulti area :shape) dispatches on the :shape key of a map.

(defmethod area :circle [{:keys [r]}] (* Math/PI r r)) adds one case. New cases can be added from any namespace, which keeps the dispatch open for extension.

:default handles values with no method; without it, an unknown dispatch value throws IllegalArgumentException.

Dispatch can use vectors for multiple criteria: (defmulti collide (fn [a b] [(:type a) (:type b)])).

derive builds keyword hierarchies: after (derive ::square ::rect), a method for ::rect also handles ::square.

multimethods

(defmulti area :shape)
(defmethod area :circle [{:keys [r]}] (* 3 r r))
(defmethod area :rect [{:keys [w h]}] (* w h))
(defmethod area :default [s] (str "unknown " (:shape s)))

(println (area {:shape :circle :r 2}))
(println (area {:shape :rect :w 3 :h 4}))
(println (area {:shape :hex}))

(derive ::square ::box)
(defmulti label identity)
(defmethod label ::box [_] "box-like")
(println (label ::square))
Match this when you type.

Quiz

What decides which defmethod runs?

Quiz

What happens with no matching method and no :default?

Quiz

What does (label ::square) return?

Quiz

What does (area {:shape :hex}) return?

Check

Match the still for: Multimethods.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.