Passing a Clojure Function as java.util.Function

As in the subject, I would like to use a Java method that takes a function as an argument and provide it with a function Clojure, whether anonymous or regular. Does anyone know how to do this?

+4
source share
2 answers

java.util.function.Functionis an interface.
You need to implement an abstract method apply(T t).
Something like this should do this:

(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
+4
source

Terrier 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 macro:

(defmacro jfn [& args]
  `(as-function (fn ~@args)))
+2
source

Source: https://habr.com/ru/post/1606964/


All Articles