Why is varargs always the last parameter in a method signature?

Why should varargs be the last parameter in the method signature?

I want to know the reason.

+4
source share
2 answers

Because it simplifies the life of the compiler. There is no real reason why there could be no more arguments after that, but this would require a much more complex compiler, so the specification was written that way.

+15
source

The main reason is that otherwise it would be potentially ambiguous .

For example, how could the compiler say if the arguments are varargs or single named arguments in a long list of arguments with multiple varargs?

Imagine a method signature, for example:

 printNames(String... girls, String... boys); 

If you do printNames("Lucy", "Jo", "Paul") , is it a boy or girl?

As another example of the ambiguity that has varargs previously in the argument list, problems can arise with overloaded methods. For instance:

 printFruit(String... apples, String orange); printFruit(String... apples, String grapefruit, String orange); 

How can the compiler say if the second-last argument is a grapefruit or an extra apple?

Note that this is not unique to Java, most languages ​​that support varargs only allow at the end of the argument list for the same reason.

+9
source

Source: https://habr.com/ru/post/1397551/


All Articles