Search code examples
clojure

Importing function from other file in clojure


How can i import a function in closure? Suppose i have two files:

test.clj
test2.clj

I want to use the function from test2 in test.

I have tried the following in test, but this is not working:

(namespace user :require test2)

How am a able to import a function in another file?

Basically want to do `from lib import f in python


Solution

  • In file test.clj:

    (ns test
      (:require [test2 :as t2]))
    
    (defn myfn [x]
      (t2/somefn x)
      (t2/otherfn x))
    

    In the above example, t2 is an alias for the namespace test2. If instead you prefer to add specified symbols from the namespace use :refer:

    (ns test
      (:require [test2 :refer [somefn otherfn]]))
    
    (defn myfn [x]
      (somefn x)
      (otherfn x))
    

    To refer to all public symbols in the namespace, use :refer :all:

    (ns test
      (:require [test2 :refer :all]))
    
    (defn myfn [x]
      (somefn x)
      (otherfn x))