Passing a Clojure function as java.util.Function

荒凉一梦 提交于 2020-12-30 07:41:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!