Posts Tagged ‘clojure’

Clojure Closures In Java

As part of a team conversation this morning, I worked up a quick Java translation of some more-interesting-than-it-looks Clojure code. It’s a good example of how lexical closures map to objects.

The code we started out with was this:

(defn make-adder [x]
  (let [y x]
    (fn [z] (+ y z))))

(def add2 (make-adder 2))

(add2 4)

What this code does is define and return a new type of function that adds values to the constant x. In Java, it looks like this: Continue Reading…