David J.
David J.

Reputation: 32705

Forward-declaring a var from another namespace in Clojure?

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

At the moment, this is what I've 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.

Upvotes: 4

Views: 454

Answers (1)

xsc
xsc

Reputation: 6073

I think the solution you already have is the easiest one. If you wrap it into a macro it doesn't even look that bad anymore:

(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 it with:

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

Upvotes: 3

Related Questions