Defining multimethods is another way to realize polymorphism. The multimethod has a strong dispatch mechanism for polymorphism. Let's see how it works.
You need to add the math.numeric-tower
to your project.clj
file to run samples (or any other dependency management you are using):
:dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/math.numeric-tower "0.0.4"] ]
Let's see how to define and use multimethods.
The defmulti
creates new multimethods, and the defmethod
creates and implements a new method of multimethod associated with a dispatch value.
The following code shows an example of the defmulti
of the calculation of the volume of shapes. The first argument is the name of the multimethod and the second argument is the dispatch function:
(defmulti volume :shape) ;;=> nil
Now we will define a method for the calculation of cube:
(defmethod volume :cube [shape...