Polymorphism

One useful aspect of object orientation is polymorphism; while polymorphism happens to be associated with that style, it’s in no way exclusive to object-oriented programming. Clojure provides two common ways to achieve runtime polymorphism. Let’s look at each of these in turn.

Multimethods

Multimethods provide an extremely flexible dispatching mechanism using a selector function associated with one or more methods. The multimethod is defined using defmulti, and each method is defined using defmethod. For example, if we had different shapes and we wanted to write a multimethod to calculate the area, we could do the following:

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

Get Web Development with Clojure, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.