将 Clojure 函数作为 java.util.Function 传递
Passing a Clojure function as java.util.Function
在主题中,我想使用一个 Java 方法,将函数作为参数并为其提供一个 Clojure
函数,无论是匿名函数还是常规函数。任何人都知道如何做到这一点?
java.util.function.Function
是一个接口。
你需要实现抽象方法apply(T t)
.
应该这样做:
(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
Terje 接受的答案是绝对正确的。但是你可以使用一阶函数让它更容易使用:
(defn ^java.util.function.Function as-function [f]
(reify java.util.function.Function
(apply [this arg] (f arg))))
或一个宏:
(defmacro jfn [& args]
`(as-function (fn ~@args)))
在主题中,我想使用一个 Java 方法,将函数作为参数并为其提供一个 Clojure
函数,无论是匿名函数还是常规函数。任何人都知道如何做到这一点?
java.util.function.Function
是一个接口。
你需要实现抽象方法apply(T t)
.
应该这样做:
(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
Terje 接受的答案是绝对正确的。但是你可以使用一阶函数让它更容易使用:
(defn ^java.util.function.Function as-function [f]
(reify java.util.function.Function
(apply [this arg] (f arg))))
或一个宏:
(defmacro jfn [& args]
`(as-function (fn ~@args)))