Search code examples
clojureclojure-java-interop

Field accessors as functions in clojure?


Is there a way to convert field accessors to functions? I was really surprised when I tried to do this

(map .x [o1 o2])

but instead had to do this

(defn x [o] (.x o))
(map x [o1 o2])

which seems rather unnecessary. Is there a way to have this function created for you?


Solution

  • You could write your own wee macro to generate the anonymous function:

    (defmacro field [m] `(fn [x#] (. x# ~m)))
    

    Then, for example,

    ((field x) (java.awt.Point. 3 5))
    ;3