Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Clojure function as java.util.Function

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?

like image 660
miau Avatar asked Sep 11 '15 13:09

miau


People also ask

How do you call a Java function in Clojure?

Java methods can be called by using the dot notation. An example is strings. Since all strings in Clojure are anyway Java strings, you can call normal Java methods on strings.

Is Clojure interoperable with Java?

Overview. Clojure was designed to be a hosted language that directly interoperates with its host platform (JVM, CLR and so on). Clojure code is compiled to JVM bytecode. For method calls on Java objects, Clojure compiler will try to emit the same bytecode javac would produce.

How do you return a function in Clojure?

There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when , the function will always return something, in these cases nil .

Does Clojure have closures?

Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.


2 Answers

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)))
like image 33
Leon Barrett Avatar answered Sep 30 '22 07:09

Leon Barrett


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
like image 190
Terje Dahl Avatar answered Sep 30 '22 05:09

Terje Dahl