Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous varargs method call compilation error

method(1);  // This works -

void method(int... x) { }
void method(int x) { }  // - this method is called

If I add a varargs parameter to the second method, I get a "reference to method is ambiguous" compilation error:

method(1);  // This now fails

void method(int... x) { }
void method(int x, String... y) { }  // adding String... y causes a problem.

As the String... y argument(s) can be left "blank", why doesn't Java still pick that method? Thanks, and apologies if there is a closely matching explanation on SO; I did look for one.

like image 354
user2911290 Avatar asked Oct 18 '25 07:10

user2911290


1 Answers

The compiler always makes the choice to use the most specific method.

In the first case, because the number of the arguments exactly matches void method(int x), it is the one that's being called.

In the second case, the number of the arguments don't match any case, and it can be called from both methods, resulting the ambiguity.

Check the JLS - 15.12.2. Compile-Time Step 2: Determine Method Signature for details.

like image 148
Maroun Avatar answered Oct 19 '25 20:10

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!