ClojureDocs

导航

命名空间

defmethod

clojure.core

1.0 起可用 (源代码)
  • (defmethod multifn dispatch-val & fn-tail)
Creates and installs a new method of multimethod associated with dispatch-value. 
4 Examples
(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] (get 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)
"Bonjour!"
;; Methods can be given a name.  Very useful in stack traces.
(defmethod foo "a" name-of-method [params] "was a")
(defmulti ticket-price :customer-status)

(defmethod ticket-price :student
  ;; Everything after the dispatch value is passed to fn.
  student-price
  [customer]
  10.0)

(defmethod ticket-price :professional
  professional-price
  [customer]
  650.0)
See Also

Creates a new multimethod with the associated dispatch function. The docstring and attr-map are op...

Added by kumarshantanu

Removes the method of multimethod associated with dispatch-value.

Added by klauern

Removes all of the methods of multimethod.

Added by klauern

Given a multimethod, returns a map of preferred value -> set of other values

Added by klauern

Given a multimethod, returns a map of dispatch values -> dispatch fns

Added by klauern

Given a multimethod and a dispatch value, returns the dispatch fn that would apply to that value, ...

Added by klauern
0 Notes
No notes for defmethod