How can I take a large existing Java project and start to add Clojure modules? For example, in the code below, I’d like to make the following functions available in Java: state?, zip?, state-list, zipcode-list. The two predicates will return a boolean, but the “getters” will return arrays.
(def *states* (list "NJ" "NY" "CA"))
(def *zipcodes* (list 12345 54343 98765))
(defn member [x sq]
(if (seq sq)
(if (= x (first sq))
sq
(recur x (rest sq)))))
(defn state? [aState]
(not (= (member aState *states*) nil)))
(defn zip? [aZip]
(not (= (member aZip *zipcodes*) nil)))
(defn state-list []
*states*)
(defn zipcode-list []
*zipcodes*)
;; ---------------
(state? "AA")
(state? "CA")
(zip? 11111)
(zip? 12345)
I would compile it using leiningen then add the jar file to my java project as a build dep. Here is a great video on using leiningen.
then you would call it directly from java. Leiningen has an uberjar option that bulds in clojure and all your clojure dependencies so you only have to worry about one file. I like this because its less work.
A more java friendly approach would be to add an ant task to build it along with the java project its just a little more work
for the functions that need to return proper java arrays call
to-arrayon themcontrary to many of the top “calling clojure from java” hits you should not need to call the clojure runtime RT.
PS: my favorite tag line “I would like to use a java library called clojure” I asked Rich he said this was cool 😉