Search code examples
clojure

Shadowing core functions in namespaces in Clojure


I'm trying to shadow a core function in one of my namespaces. The codes work like below:

core.clj:

(ns test.core
  (:refer-clojure :exclude [zero?])
  (:require [test.z :refer [zero?]]))

(defn -main
  (prn (zero? 1)))

z.clj:

(ns test.z
  (:refer-clojure :exclude [zero?]))
(defn zero? [x] (+ x 1))

When running, it shows error messages:

; (err) WARNING: zero? already refers to: #'clojure.core/zero? in namespace: test.z, being replaced by: #'test.z/zero?

I'm not sure if Clojure permits this, can anyone help me? Thanks a lot!


Edit: That seems to be the problem, but the error message is really confusing. Anyway, thanks a lot!


Solution

  • Your -main function is missing an argument declaration so, as the code stands, it is not legal. However, if you add the arguments, it works as expected with the standard Clojure CLI:

    seanc@DESKTOP-30ICA76:~/clojure/test.core$ cat src/test/core.clj
    (ns test.core
      (:refer-clojure :exclude [zero?])
      (:require [test.z :refer [zero?]]))
    
    (defn -main [& args]
      (prn (zero? 1)))
    seanc@DESKTOP-30ICA76:~/clojure/test.core$ cat src/test/z.clj
    (ns test.z
      (:refer-clojure :exclude [zero?]))
    (defn zero? [x] (+ x 1))
    seanc@DESKTOP-30ICA76:~/clojure/test.core$ clojure -M -m test.core
    2
    seanc@DESKTOP-30ICA76:~/clojure/test.core$ clj
    Clojure 1.10.2
    user=> (require '[test.core])
    nil
    user=> (test.core/-main)
    2
    nil
    user=>
    

    As you can see, there are no warnings. It's possible the WARNING shows up because of the error in your -main function (missing arguments). It's also possible that whatever tooling you are using to load/run the code is doing something wrong/inadvisable -- but you haven't given any details about that.