Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

Apology if it is a naive question. I am pretty new to Clojure.

I have a question about cross namespace extension with protocol.

Let's say I have a name space ns-a and within it I use protocol to extend the java String, to add a method called myStringMethod.

How do I use this myStringMethod from another namespace, say ns-b, with code for example below?

(let [hello "hello"] (. hello myStringMethod)) 

Do I need to require name space ns-a, even though I would never use anything from namespace ns-a? Or compiler will scan all source code to ensure the extension is loaded?


1 Answer

+1 vote

You need to load any code that extends protocols before you use it.

One note that you won't call protocol methods via Java interop (with a .) - that will just try to invoke a method on the String instance directly (and it doesn't exist). You should call the function like any other Clojure function.

(let [hello "hello"] (myStringMethod hello))
Thanks for the tip of calling clojure protocol function.

What do you mean by `load code before using it` for protocol extension?

Require the namespace where the extension is defined? Or should each namespace has a copy of the extension code? Or some other way?
With `require`