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?
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.
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.
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 .
Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.
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)))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With