Calling Java code from Clojure

I’ve been writing a lot of Java in the last 8 months, and only two weeks ago discovered the joy of Clojure. It is such a pleasant and well-designed language. It is a Lisp, but it runs natively on the JVM (Java Virtual Machine). All of the built-in data structures are immutable but use efficient semantics when updating a value. The = function works as expected.

One thing I have been using it regularly for is sort of like a Bash for the JVM, I keep a scratch.clj file in Dropbox, and I hook that up to an Emacs buffer using @bbatsov’s cider package. That setup lets me type in some clojure code, hit Ctrl-j and then the previous expression is evaluated. You can easily call into Java code, for example:


(org.apache.commons.codec.binary.Hex/encodeHexString (.getBytes "foo"))
"666f6f"

This is a quick way to test out some Java code without having to make a new class, or open an IDE and make “New Project 79” just to see a line of code in action.

Each .clj file has a namespace defined like this:


(ns scratch.core
  "tlehman's scratch file"
  (:import org.apache.commons.codec.binary.Hex))

(Hex/encodeHexString (.getBytes "foo"))
"666f6f"

The :import keyword performs the same function as the import statement in Java, but it can be evaluated dynamically in a repl or in emacs.

Another thing that is nice is the class function, which will tell you the class of the thing you pass in.


(class :import)
clojure.lang.Keyword

The keyword :import has the same syntax as Ruby symbols, but in Clojure they are called keywords, and they are also functions, since (:import org.apache.commons.codec.binary.Hex) evaluates.

You can see keywords in action here, take the literal map {:name "Tobi"}, then call the keyword function (:name {:name "Tobi"}):


(:name {:name "Tobi"})
"Tobi"

I’ve only just started down the clojure rabbit hole, but I really like the language, partly for it’s thoughtful design, but the practical use of having a REPL for all my Java work keeps me coming back.