47

I'am wrapping a java lib into clojure, but i have problems dealing with variable length arguments. Say,

TestClass.aStaticFunction(Integer... intList){/*....*/}

How could i call this function in clojure?

qiuxiafei
  • 5,827
  • 5
  • 30
  • 43
  • possible duplicate of [Implement a Java interface method with a variable number of args in Clojure](http://stackoverflow.com/questions/9103777/implement-a-java-interface-method-with-a-variable-number-of-args-in-clojure) – Jeremy Jul 28 '12 at 15:41

3 Answers3

64

Since Java varargs are actually arrays, you can call vararg functions in Clojure by passing an array.

You could convert a Clojure seq (maybe by using Clojure's variety of variable argument functions) into an array:

 (TestClass/aStaticFunction (into-array Integer [(int 1),(int 2)]))

or

(defn a-static-function-wrapper [& args]
  (TestClass/aStaticFunction (into-array Integer args))

Or make an array and set its indices manually

(TestClass/aStaticFunction (doto (make-array Integer 3)
                              (aset 0 first-element)
                              (aset 1 second-element)
                              (aset 2 third-element)))
Zach L
  • 16,072
  • 4
  • 38
  • 39
9

Java variable length arguments actually want an array as input.

So in Clojure the call should be something like:

(TestClass/aStaticFunction (into-array Integer some-sequence-of-integers))
mikera
  • 105,238
  • 25
  • 256
  • 415
5
(TestClass/aStaticFunction (to-array '(1 2 3 4 5)))

For e.g.

(java.util.Arrays/asList (to-array '(1 2 3 4 5)))
jittakal
  • 919
  • 6
  • 8