7

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?

3
  • 3
    (reify java.util.function.Function)? Commented Sep 11, 2015 at 15:07
  • 2
    The reify approach works but is overly verbose. I think we're going to see more and more Java APIs using the functional interfaces in java.util.function, so it would be good to fix this in Clojure itself. Clojure functions already implement Runnable and Callable. Commented Feb 8, 2016 at 12:57
  • @glts are you aware of any discussion on the topic of extending the java.util.function.Function interface for java.lang.IFn or have java.lang.AFn implement it? It's still not done and I'm wondering why? github.com/clojure/clojure/blob/… Could it be that the Function also has a compose & andThen method, besides the main apply? Commented Oct 24, 2022 at 2:24

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

Comments

7

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)))

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.