Why does varargs
have to be the last parameter in method signature?
I want to know the reason.
Why does varargs
have to be the last parameter in method signature?
I want to know the reason.
Because it makes the compiler's life simpler. There's no real reason why it couldn't have more arguments after, but it would require a much more complex compiler and so the spec was written that way.
code
, and all the others in names
. –
Kersey The main reason is because it would be potentially ambiguous otherwise....
For example, how could the compiler tell whether arguments are varargs or separate named arguments in a long list of arguments with multple varargs?
Imagine a method signature like:
printNames(String... girls, String... boys);
If you do printNames("Lucy", "Jo", "Paul")
is Jo a boy or a girl?
As another example of ambiguity, having varargs earlier in the argument list could cause problems when there are overloaded methods. For example:
printFruit(String... apples, String orange);
printFruit(String... apples, String grapefruit, String orange);
How can the compiler tell whether the second-to-last argument is a grapefruit or an additional apple?
Note that this isn't unique to Java, most languages that support varargs only allow then to be at the end of the argument list for the same reason.
© 2022 - 2024 — McMap. All rights reserved.
C family of language
creators here [ C Family Interview](gotw.ca/publications/c_family_interview.htm) where Gosling says "I had this personal rule that by and large I didn't put anything in just because I thought it was cool. Because I had a user community the whole time, I'd wait until several people ganged up on me before I'd stick anything in. If somebody said, "Oh, wouldn't that be cool," by and large I ignored them until two or three people came up to me and said "Java ought to do this." Then I'd start going, well, maybe people will actually use it." – Nightingale