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
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values.
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.
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.
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[].
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.
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() };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With