Clojure Goodness: Invoke a Java Method With a Varargs Parameter
Make it easy to get Java and Clojure to work together.
Join the DZone community and get the full member experience.Join For Free
Sometimes we want to invoke Java methods from our Clojure code. If the Java method accepts variable arguments (varargs) parameter and we want to invoke the method from Clojure, we must pass an array as an argument. To create an array in Clojure we can use several functions. The
to-array function will transform a collection to an
Object type. For primitive type arrays we can use for example
int-array to get a
int array. The function
into-array is the most flexible function. This function accepts a sequence argument and optionally the class type of the resulting array. Once we have the array we can use it as an argument value for the varargs parameter of the Java method we want to invoke.
In the following example, we use
short-array to invoke a Java method with varargs parameter and see how we can build different array types:
Written with Clojure 1.10.1.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.