问题
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?
回答1:
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
回答2:
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)))
来源:https://stackoverflow.com/questions/32525255/passing-a-clojure-function-as-java-util-function