Forward declaration of var from another namespace in Clojure?

I know how to redirect a var declaration for the current namespace. Instead, I want to declare var from another namespace. How can I do it? This will help me eliminate the circular load dependency.

At the moment, this is what I tried:

; this_ns.clj
(ns my-project.this-ns
  (:require ...))
(ns my-project.other-ns)
(declare other-func)
(ns my-project.this-ns) ; return to original namespace
(defn func-1
  []
  (my-project.other-ns/other-func))

It works, but I don't like it.

+4
source share
1 answer

I think the solution that you already have is the easiest. If you wrap it in a macro, it won’t even look so bad:

(defmacro declare-extern
  [& syms]
  (let [n (ns-name *ns*)]
     `(do 
        ~@(for [s syms]
            `(do 
               (ns ~(symbol (namespace s)))
               (declare ~(symbol (name s)))))
        (in-ns '~n))))

Call the following address:

(declare-extern my.extern.ns/abc) ;; => #<Namespace ...>
my.extern.ns/abc                  ;; => #<Unbound Unbound: #'my.extern.ns/abc>
+3
source

All Articles