So, there is yet another new language feature in the Tiger early-access compiler. I already know about JSRs 14 (generics) and 201 (enums, autoboxing, enhanced for loop and static imports). But the "Test.java" in the early-access compiler also contains some "varargs" examples.
I couldn't find any mention of this syntax change in JSRs 14 or 201. A little digging and I uncovered that it is most likely some form of JSR 65: Concise Object-Array Literals.
Basically, this language addition means that the compiler will
automagically wrap the trailing arguments to a method call in a
Object[] {...}
expression.
For example, say you wanted a "printf" method that printed out a list of objects separated by some separator string. Traditionally, you might code up something like this (note I've used the new enhanced for loop syntax):
public static void myprintf(String seperator, Object[] args) { String sep = ""; for (Object o : args) { System.out.print(sep); System.out.print(o); sep = seperator; } System.out.println(); } ... myprintf(", ", new Object[] {"a", "b", "c"});
That's fine, but it is annoying to always have to type new
Object[] {
. The new JSR 65 syntax allows you to declare that
last parameter to myprintf()
as a "varargs catch-all". Then
any "left over" parameters to a call to myprintf()
will
be wrapped in a new Object[] {...}
expression by the
compiler.
To do this, you use the new ellipsis ...
token:
public static void myprintf(String seperator, Object[] args...) {
String sep = "";
for (Object o : args) {
System.out.print(sep);
System.out.print(o);
sep = seperator;
}
System.out.println();
}
You can call the method like this:
int i = 1; double x = 1.0; String s = "Hello"; // vararg example myprintf(", ", "a", "b", "c"); // above is equivalent to myprintf(", ", new Object[] {"a", "b", "c"}); // example with autoboxing, too myprintf(", ", i, x, s); // equivalent to myprintf(", ", new Object[] {new Integer(i), new Double(x), s});
The output of the above is:
a, b, c a, b, c 1, 1.0, Hello 1, 1.0, Hello
Hmm... I think I've said something about complexity already.