Clojure协议/函数优先级

3

在使用Clojure时,我们有以下内容:

(defprotocol Greeter (hello [args] "Say hello"))

(extend-protocol Greeter
   String
   (hello [this] (str "Hello " this)))

(hello "world")    ; "Hello world"

到目前为止,一切顺利。然后我们添加:
(defn hello [args] (str "Wassup " args "?"))

这将改变上一个表单的输出为:

(hello "world")    ; "Wassup world?"

有没有办法让协议优先于函数执行?
2个回答

5

有没有办法让协议优先于方法?

你不能将 defndefprotocol 混合使用。这是因为 defprotocol 实际上在当前命名空间中生成一个函数绑定。当按照此顺序运行代码时,请注意警告:

user=> (defn hello [args] (str "Wassup " args "?"))
#'user/hello
user=> (defprotocol Greeter (hello [args] "Say hello"))
Warning: protocol #'user/Greeter is overwriting function hello
Greeter

协议文档中解释了提供默认实现的正确方法是使用Object

(defprotocol Greeter (hello [args] "Say hello"))

(extend-protocol Greeter
   Object
   (hello [this] (str "Wassup " this "?")))

(extend-protocol Greeter
   String
   (hello [this] (str "Hello " this)))

(hello "world")    ; "Hello world"

(hello 1)    ; "Wassup 1?"

2

协议方法是函数,因此像其他变量一样,如果您想要具有相同名称的两个变量,则必须将它们放在单独的命名空间中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接