m0skit0
m0skit0

Reputation: 25873

Understanding multimethods dispatching

I can understand how this works:

(defmulti area :Shape)
(defmethod area :B [x] (println "Rect"))
(defmethod area :C [x] (println "Circle"))
(defmethod area :default [x] (do (println "Unknown") (:Shape x)))
(area {:Shape :B})
=> Rect
nil
(area {:Shape :Bb})
=> Unknown
:Bb

But by simply changing :Shape to :Shap, I stop understanding how this is being dispatched:

(defmulti area :Shap)
(defmethod area :B [x] (println "Rect"))
(defmethod area :C [x] (println "Circle"))
(defmethod area :default [x] (do (println "Unknown") (:Shap x)))
(area {:Shap :B})
=> Unknown
:B
(area {:Shap :C})
=> Unknown
:C

Clojure 1.5.1 on Eclipse with Counterclockwise plugin

Upvotes: 3

Views: 119

Answers (1)

amalloy
amalloy

Reputation: 91907

Multimethods don't like being redefined with a new dispatch function. This is a rather controversial feature, but it's the way things are. In order to change a multimethod's dispatch function, you must first def it to something which is not a multimethod (for example, to nil).

(defmulti area :Shape)

(def area nil)

(defmulti area :Shap)

Upvotes: 7

Related Questions