Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type vararg?

Tags:

java

I have a method like:

void foo(int x, Grok... groks);

There's no way to define a method that returns a type of varargs, right? Ideally I want an additional util method:

foo(25, new Grok(), new Grok(), generateMoreGroks());

public Grok... generateMoreGroks() {
    return new Grok[] {
        new Grok(), new Grok(), new Grok() };
}

right?

---- More info --------------

The issue with the above is that we can't mix a few Grok instances allocated there with an array of Groks:

 "new Grok(), new Grok(), generateMoreGroks());"

and I don't think that's legal, unless you could define a method to return a type of vararg (I guess).

Thanks

like image 627
user291701 Avatar asked Sep 10 '11 16:09

user291701


People also ask

What is Vararg?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values.

Can Vararg be null?

Note that vararg parameters are, as a rule, never nullable, because in Java there is no good way to distinguish between passing null as the entire vararg array versus passing null as a single element of a non-null vararg array.

What is a Vararg Kotlin?

Variable Number of Arguments (Varargs) In Kotlin, a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body. A function may have only one vararg parameter.

How do you handle varargs in Java?

Syntax of Varargs Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].


2 Answers

You can do,

Grok[] generateMoreGroks() {

If a method takes a varargs parameter, it is the same as taking an array.

Now you need to overload foo to allow it to take some Grok instances, and the rest as varargs,

foo(int x, Grok... rest)
foo(int x, Grok g1, Grok... rest)
foo(int x, Grok g1, Grok g2, Grok... rest)
foo(int x, Grok g1, Grok g2, Grok g3, Grok... rest)

Where foo methods are like,

foo(int x, Grok g1, Grok... rest) {
     Grok[] groks = new Grok[rest.length + 1];
     groks[0] = g1;
     System.arrayCopy(rest, 0, groks, 1, rest.length);
     foo(x, groks);
}

This is a bit ugly.

like image 132
sbridges Avatar answered Oct 02 '22 14:10

sbridges


No there isn't... but change the function signature and that will work just fine.

public Grok[] generateMoreGroks() {
    return new Grok[] {
        new Grok(), new Grok(), new Grok() };
}
like image 41
linuxuser27 Avatar answered Oct 02 '22 13:10

linuxuser27