开发者

How can I invoke a Clojure multimethod based on the presence of an interface as opposed to a class?

开发者 https://www.devze.com 2023-02-02 02:46 出处:网络
I know that multimethods are often dispatches based on class, but is there开发者_开发百科 a way to dispatch based on an interface which is implemented instead? Multimethods allow you to specify your o

I know that multimethods are often dispatches based on class, but is there开发者_开发百科 a way to dispatch based on an interface which is implemented instead?


Multimethods allow you to specify your own dispatch function. So you can dispatch based on any predicate! The following code dispatches based on the interface implemented by the argument:

(defmulti process-collection
  (fn [arg1 & _]
    (cond
      (instance? java.util.List arg1) :list
      (instance? java.util.Set arg1) :set
      :else :coll)))

(defmethod process-collection :list
  [list-to-process]
  ())

(defmethod process-collection :set
  [set-to-process]
  ())

(defmethod process-collection :coll
  [coll-to-process]
  ())
0

精彩评论

暂无评论...
验证码 换一张
取 消