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?

Racil Hilan
25.4k13 gold badges56 silver badges61 bronze badges
asked Sep 11, 2015 at 13:57
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
answered Feb 8, 2016 at 11:58
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)))
nha
18.1k15 gold badges95 silver badges141 bronze badges
answered Apr 4, 2017 at 0:08

1 Comment

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.