【发布时间】:2011-12-21 16:47:58
【问题描述】:
假设我有两个协议:
(defprotocol A
(f [this]))
(defprotocol B
(g [x y]))
我想将协议 B 扩展到支持协议 A 的所有实例:
(extend-protocol A
String
(f [this] (.length this)))
(extend-protocol B
user.A
(g [x y] (* (f x) (f y))))
主要动机是避免将 B 单独扩展到 A 可能扩展到的所有可能的类,甚至扩展到其他人可能将 A 扩展到的未知未来类(想象一下,如果 A 是公共 API 的一部分,例如)。
但是这不起作用 - 你会得到如下内容:
(g "abc" "abcd")
=> #<IllegalArgumentException java.lang.IllegalArgumentException:
No implementation of method: :g of protocol: #'user/B found for
class: java.lang.String>
这可能吗?如果没有,是否有合理的解决方法来实现相同的目标?
【问题讨论】:
标签: clojure protocols abstraction