Closures Varargs Examples - UnquietCode/Closures-for-Java GitHub Wiki
Using Closures requires a good understanding of how vararg methods work in Java. These code examples should serve to clarify what to expect.
Generally the only exception made is that while normally passing the argument null
into a varargs produces a null
object inside the method, the Closure classes package that into an array of length 1 with 1 Object with value null
. This means that null
can be used as a valid parameter to a Closure. You should expect what you pass, after all.
public void varargTestX() {
out(tryit()); // 0
out(tryit(1)); // 1
out(tryit(1, 2)); // 2
//out(tryit(null)); // NullPointerException
out(tryit(new Object[] {})); // 0
out(tryit(new Object[] {null})); // 1
out(catchNull(null)); // 1 (null)
out(catchNull(null, null)); // 2
out(whoGetsIt()); // empty
out(whoGetsIt(null)); // varargs
out(whoGetsIt(new Object[] {})); // varargs
}
private String tryit(Object...args) {
return args.length + "";
}
private String catchNull(Object...args) {
if (args == null)
return 1 + " (null)";
else
return args.length + "";
}
private String whoGetsIt() {
return "empty";
}
private String whoGetsIt(Object...args) {
return "varargs";
}
Additionally, arrays are a bit tricky at first when dealing with vararg methods. When you pass a series of objects they are converted to an array. When you pass an array of the same type the received array implicitly the same. However, if you pass an array with other parameters, the array is added to the generated array. (If you're confused, join the club. Look below for some clarification.)
public void arrayPassingTest() {
String arr[] = {"Alice", "Bob"};
out(arrayPass(arr));
out(arrayPass(arr, "Steve"));
out(arrayPass("Alice", "Bob"));
}
public void objectArray() {
String arr[] = {"Alice", "Bob"};
Object x = arr;
out(arrayPass(arr));
out(arrayPass("work"," thing"));
out(arrayPass(new Object[]{"Potato", "It's not a tuber!"}));
out(arrayPass(x));
}
private String arrayPass(Object...args) {
return args.length + "";
}