3

When calling a Clojure function from Java, what's the best way to specify named arguments to the function?

I have the following function:

(defn myFn [a b & {:keys [c d] :or {c 1 d 2}}]
   ; do something
   )

And I currently call it from Java with lines like this:

IFn myFn = Clojure.var("my.namespace", "myFn");
myFn.invoke(5, 6, Clojure.read(":c"), 7, Clojure.read(":d"), 8);

I find the Clojure.read... parts of the above statement verbose. Is there a simpler way to make this call?

2
  • Why don't you use a function with arity 4? Commented Oct 11, 2015 at 20:46
  • Because the arguments are optional. I also call the same function without c and d. Commented Oct 23, 2015 at 15:01

1 Answer 1

5

The question is not about how to pass named argument, but how to create keywords in Java code:

import clojure.lang.Keyword;
// others omitted...
myFn.invoke(5, 6, Keyword.find("c"), 7, Keyword.find("d"), 8);

Clojure.read would be considered too cumbersome for the task and too dangerous as it can read in any code.

Sign up to request clarification or add additional context in comments.

4 Comments

You seem to have a typo: invokde should be invoke.
This is still verbose. Is there anything shorter? Or is there a better way to design this interface between clojure and Java? Like using clojure prototypes or multi-methods?
@Jason Thanks, fixed. Regarding the further question, I don't see any shorter/better ways than this method invocation with arguments prepared. Not much redundancy here to be removed.
Hmmm... I feel an unsettling dissatisfaction with this answer. I suppose if I factored out the Keyword.find("c") and "d" bits into constants then they can be reused and the call to invoke will be shorter. So I accept your answer, but part of me is still waiting for something better :-)

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.