David
David

Reputation: 3026

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

Upvotes: 2

Views: 1544

Answers (2)

Steffan Westcott
Steffan Westcott

Reputation: 2201

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))

Upvotes: 4

Erp12
Erp12

Reputation: 652

Your namespace syntax is a bit off. I usually refer to this cheat-sheet when I need a reminder.

I think the following is the syntax you are looking for.

;; In test.clj
(ns test
  (:require [test2 :refer [some-symbol-to-import]]))

Upvotes: 3

Related Questions