Clojure protocol/function priority

clojure

Solution

Is there a way to make the protocol take priority over the method?

You can't mesh `defn` with `defprotocol`. This is because `defprotocol` actually generates a binding for a function in your current namespace. Notice the warning you get when you run your code in this order:

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

The Protocols documentation explains that the correct way to provide a default implementation is to use `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?"

Problem

Working with Clojure, we have the following: ``` (defprotocol Greeter (hello [args] "Say hello")) (extend-protocol Greeter String (hello [this] (str "Hello " this))) (hello "world") ; "Hello world" ``` So far, so good. Then we add: ``` (defn hello [args] (str "Wassup " args "?")) ``` Which changes the output of the previous form to: ``` (hello "world") ; "Wassup world?" ``` Is there a way to make the protocol take priority over the function?

Original source