1.3.0 permalink Arrow_down_16x16

defmethod

clojure.core

  • (defmethod multifn dispatch-val & fn-tail)
Creates and installs a new method of multimethod associated with dispatch-value.

3 Examples top

  • (defmulti service-charge (fn [acct] [(account-level acct) (:tag acct)]))
    (defmethod service-charge [::acc/Basic ::acc/Checking]   [_] 25)
    (defmethod service-charge [::acc/Basic ::acc/Savings]    [_] 10)
    (defmethod service-charge [::acc/Premium ::acc/Account] [_] 0)
  • ;this example illustrates that the dispatch type
    ;does not have to be a symbol, but can be anything (in this case, it's a string)
    
    (defmulti greeting
      (fn[x] (x "language")))
    
    ;params is not used, so we could have used [_]
    (defmethod greeting "English" [params]
     "Hello!")
    
    (defmethod greeting "French" [params]
     "Bonjour!")
    
    ;then can use this like this:
    (def english-map {"id" "1", "language" "English"})
    (def  french-map {"id" "2", "language" "French"})
    
    =>(greeting english-map)
    "Hello!"
    =>(greeting french-map)
    "Bounjour!"
    
  • ;; Methods can be given a name.  Very useful in stack traces.
    (defmethod foo "a" name-of-method [params] "was a")
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1609 top

(defmacro defmethod
  "Creates and installs a new method of multimethod associated with dispatch-value. "
  {:added "1.0"}
  [multifn dispatch-val & fn-tail]
  `(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail)))
Vars in clojure.core/defmethod:
Used in 0 other vars

Comments top

No comments for defmethod. Log in to add a comment.