Mostly about Clojure and ClojureScript

Using the Clojure REPL With Java or Scala

Jul26th, 20162:26 pm

Clojure is a tool that enables interactive development and runtime
inspection. Even when we work in other programming languages,
Clojure can still be useful. Especially when that other language lives
on the JVM.

Let’s take Scala for example. Scala has a REPL. The REPL can be used
to test-drive software in development. But it doesn’t really let you
inspect a running program when you didn’t start it with sbt
console. So let’s use Clojure for that. We will walk through a simple
Scala program that allows runtime inspection of an otherwise unknown
state.

We’ll need an sbt project for this example. Make a directory and put a
build.sbt in it. The only dependency in this example is Clojure.

We’ll be using
Clojure’s Java API. In
Scala var is a reserved keyword, so I’m renaming it to cvar, since
I don’t like the backticks in my code.

Next, let’s create an object that will contain some random value:

123

objectBusinessLogic{valx=Math.random()// I wonder what this value is at runtime... }

Also, let’s create an App so we can run our program with sbt run:

12

objectMainextendsApp{}

If we would execute sbt run, we would never know the value of x in
BusinessLogic. We could add a println, but what if x was a var
and it’s value would change over time? Clojure lets us inspect this
value at any given point in time. We’ll start a
socket server
that is available since Clojure 1.8.0.

This may seem a little intimidating, so I’ll explain it line by line.
On line 2 we get a reference to Clojure’s require so we can… yes,
require namespaces. On line 3 we read a string so we get the symbol
that require needs to load the clojure.core.server namespace. On
line 4 we get a reference to the start-servervar. On line 5 we
define a bunch of settings. Their meaning can be found
here.

This doesn’t do much except taking care that Clojure is initialized
(for more info, read the last paragraph in
this Stackoverflow answer).

This Scala example translates fairly straightforward to Java. Now don’t tell your
boss you’re using a different programming language. After all, Clojure
is just a Java library that gives you superpowers :-).

PS: it may be wise to turn this off in production because of the
security risk; on the other hand, a Clojure REPL has saved my day more
than once in the past!