Search code examples
clojurenamespacesread-eval-print-loop

Clojure - same function name different namespace


I am trying to do the following:

(ns ns-test.core
  (:use [ns-test.a :as a]
    [ns-test.b :as b]))

(def test-map {:key "a"})

(defmulti print-ns :key)
(defmethod print-ns "a" [input-map]
  (a/foo input-map))
(defmethod print-ns "b" [input-map]
  (b/foo input-map))

with namespaces a and b that look like this:

(ns ns-test.a)

(defn foo [x]
  (println x "I'm in namespace A."))

and

(ns ns-test.b)

(defn foo [x]
  (println x "I'm in namespace B."))

but when I try to load these classes into the REPL, I get this:

user=> (use 'ns-test.core :reload)

CompilerException java.lang.IllegalStateException: foo already refers to: #'ns-test.a/foo in namespace: ns-test.core, compiling:(ns_test/core.clj:1:1) 

Why does this conflict between a/foo and b/foo exist, and how can I prevent it? (Isn't the whole point of namespaces and namespace qualification to allow me to have two different functions of the same name?)


Solution

  • You probably wanted to :require the namespaces a and b instead of :use. :use interns the namespace symbols to the current namespace, thus the conflict.