As in topic, I'd like to use a Java method taking a Function as an argument and provide it with a Clojure function, be it anonymous or a regular one. Anyone has any idea how to do that?
2 Answers
java.util.function.Function is an interface.
You need to implement the abstract method apply(T t).
Something like this should do it:
(defn hello [name]
(str "Hello, " name "!"))
(defn my-function[]
(reify
java.util.function.Function
(apply [this arg]
(hello arg))))
;; then do (my-function) where you need to pass in a Function
Comments
Terje's accepted answer is absolutely correct. But you can make it a little easier to use with a first-order function:
(defn ^java.util.function.Function as-function [f]
(reify java.util.function.Function
(apply [this arg] (f arg))))
or a macro:
(defmacro jfn [& args]
`(as-function (fn ~@args)))
1 Comment
Jeremy Field
also see ask.clojure.org/index.php/767/…
(reify java.util.function.Function)?reifyapproach works but is overly verbose. I think we're going to see more and more Java APIs using the functional interfaces injava.util.function, so it would be good to fix this in Clojure itself. Clojure functions already implementRunnableandCallable.java.util.function.Functioninterface forjava.lang.IFnor havejava.lang.AFnimplement it? It's still not done and I'm wondering why? github.com/clojure/clojure/blob/… Could it be that theFunctionalso has acompose&andThenmethod, besides the mainapply?