View RSS Feed

Hibernate

Variadic functions (varargs)

Rate this Entry
by , 08-12-2011 at 12:47 AM (2755 Views)
Ever heard of variadic functions of varargs.
It is my favourite synthetic sugar (although I must admit i prefer cane sugar).

Variadic functions have undefine arity (the parameter is called a "vararg" (variadic argument)), meaning
that it lets you use any amount of parameters when invoking it.

For example:
Java Code:
public class MyClass
{
    private static void print(final String prefix, final int... lines)
    {
        for (final int line : lines)
            System.out.println(prefix + String.valueOf(line));
    }

    private static void print(final String prefix, final String... lines) // (*)
    {
        for (final String line : lines)
            System.out.println(prefix + line);
    }



    public static void main(final String... args)
    {
        print(":", 1, 2, 3, 4, 5);
        print(":", new int[] {1, 2, 3, 4, 5});
        //print(":"); //Would compile if we remove (*)
        print(":", "a", "b", "c");
    }

}
int... is handled just like int[], except, it lets you specify each element in the array using a parameter instead of using an array, but it still lets you use an array.
Varargs lets you use, between 0 and the maximum size of an array, parameters.
It can be used alone unlike how it is used in the code above.

One restriction with variadic functions is that you can only use up to one vararg, even if you want to use two mutually uncastable types.
So you cannot write:

Java Code:
public class MyClass
{
    private static void print(final Strings... lines, final SomeOtherClass... moreLines)
    {
        for (final String line : lines)
            System.out.println(line);

        for (final SomeOtherClass line : moreLines)
            System.out.println(line.toString());
    }
}

Submit "Variadic functions (varargs)" to Facebook Submit "Variadic functions (varargs)" to Digg Submit "Variadic functions (varargs)" to del.icio.us Submit "Variadic functions (varargs)" to StumbleUpon Submit "Variadic functions (varargs)" to Google

Updated 08-12-2011 at 05:44 AM by Hibernate

Tags: None Add / Edit Tags
Categories
Java's syntax

Comments