How do I require the namespace inside the -main function?

Suppose in Leiningen yo project I have the following files:

foo.clj:

(ns yo.foo)
(def x 234.5)

      

bar.clj:

(ns yo.bar)
(def x -15)

      

And I have a main file (core.clj):

(ns yo.core)
(require '[yo.foo :as f])
(when (= f/x 234.5) (println "Succesfully required foo."))
(defn -main [& args]
  (println (require '[yo.bar :as b]))
  ;(when (= b/x -15) (println "Succesfully required bar."))
 )

      

When I enter "lein run" on the command line, I get this output:

Succesfully required foo.
nil

      

The first line tells me that I understand how to use the function require

at the top level of the file. (Normally I would use :require

in instructions ns

.) The second line seems to indicate that I succeeded yo.bar

.

However, when I uncomment the line that contains when

in -main

, I get an exception: java.lang.RuntimeException: No such namespace: b, compiling:(yo/core.clj:6:9)

.

Is there a way to fulfill the requirement inside a function? My goal is to pass the namespace name on the command line and load that namespace. Is there any other way to do this? (I already know how to access command line arguments from -main

.)

(The problem is not that I wrapped the call require

with println

. I get the same exception if the first line -main

says only (require '[yo.bar :as b])

.)

(The title of this question makes it seem like it's the same as mine, but the question and answer doesn't address the issue of requiring a namespace from within a function.)

+3


source to share


1 answer


An operator require

inside a function is -main

not used at compile time. So the compiler cannot resolve the namespace b

and complains.



+1


source







All Articles