在主题中,我想使用一个Java函数作为参数,并为其提供Clojure
函数,无论是匿名函数还是常规函数。任何人都知道如何做到这一点?
答案 0 :(得分:5)
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
答案 1 :(得分:3)
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)))