2

I am working on a clojure function which accepts a variable number of arguments, and passes those to a java method call

(defn foo [var1 var2 & vars]
    (let [bar (.foo var1)]
        (.gaz bar var2 vars)))

This works when vars is empty, but when I put something in vars, I get

java.lang.ClassCastException: Cannot cast clojure.lang.ArraySeq to [Ljava.lang.Object;

It seems like the vars arent being spliced / interpolated into a vararg list to the method call. How can I do this? I want to use this as both

(foo a b)

and

(foo a b c d e f)

And have it calling

(.gaz bar b c d e f) ;; <- note the list is embedded
1
  • what do you mean by "expand into a list" - convert? separate out of a sequence into positional arguments? Commented Sep 21, 2014 at 3:35

1 Answer 1

4

note this this returns exactly the type your error message is asking for:

user> (into-array Object [1 2 3])
#<Object[] [Ljava.lang.Object;@571bc284>

From context, I assume .gaz is likely varargs. If so, all you need is the following:

(.gaz bar var2 (into-array Object vars))

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

2 Comments

Thanks, works like a charm. I'm not sure I fully understand why it works but I will read up on into-array
The argument needed for varargs is expected to be a Class that a normal Clojure persistent collection does not implement. By converting to a more primitive, mutable Class, we satisfy the jvm's requirements.

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.