开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜