Multimethods
Clojure offers a way to implement polymorphism with multimethods. Polymorphism is the ability of a unit of code (in our case, functions) to behave differently in different contexts, for example, based on the shape of the data received by the code. In Clojure, we also call it runtime polymorphism because the method to call is determined at runtime rather than at compile time. A multimethod is a combination of a dispatch function and of one or more methods. The two main operators for creating those multimethods are defmulti
and defmethod
. defmulti
declares a multimethod and defines how the method is chosen with the dispatch function. defmethod
creates the different implementations that will be chosen by the dispatch function. The dispatch function receives the arguments of the function call and returns a dispatch value. This dispatch value is used to determine which function, defined with defmethod
, to invoke. Those are a lot of new terms but don't worry, the following...