Christian Lutz
Christian Lutz

Reputation: 538

Juxtaposition of Java instance methods in Clojure

Is it possible to use juxt in conjunction with methods of a Java object in Clojure?

Basically what I'm trying to achieve is

((juxt .method1 .method2) myinstance)

with .method1 and method2 being instance methods of myinstance, which is an instance of some Java class.

Thanks for your help!

Upvotes: 1

Views: 223

Answers (2)

leetwinski
leetwinski

Reputation: 17849

or just make a macro for that, which would combine normal juxt behaviour with .method behaviour. Something like this:

user> (defmacro juxt+ [& fns]
        (let [x (gensym)]
          `(fn [~x] ~(mapv #(list % x) fns))))
#'user/juxt+

for example:

(juxt+ .getName (partial str "string val: ") .getAbsolutePath vector)

expands to the following:

(fn*
  ([G__19829]
    [(. G__19829 getName)
     ((partial str "string val: ") G__19829)
     (. G__19829 getAbsolutePath)
     (vector G__19829)]))

in repl:

user> ((juxt+ .getName 
              (partial str "string val: ") 
              .getAbsolutePath 
              vector) 
         (java.io.File. "aaa"))

["aaa" 
 "string val: aaa" 
 "/Users/.../aaa" 
 [#object[java.io.File 0x34c3af49 "aaa"]]]

Upvotes: 5

superkonduktr
superkonduktr

Reputation: 655

Try encapsulating the method calls in anonymous functions:

((juxt #(.method1 %) #(.method2 %)) myinstance)

Upvotes: 4

Related Questions