methods - Varargs Java Ambiguous Call -
i'm little confused java's varargs methods:
public static int sum(int ...a) { return 0; } public static double sum(double ...a) { return 0.0; }
when tried invoke sum()
without passing argument, int
version of method invoked. don't understand why; compiler must raise error.
by contrast, following piece of code generates compiler error when try invoke sum
without argument:
public static int sum(int ...a) { return 0; } public static boolean sum(boolean ...a) { return true; }
the general rule applies here this: if 1 method signature strictly more specific other, java chooses without error.
intuituively, method signature more specific if delete entirely , other, less specific 1 applicable each existing invocation.
when presented choice between signatures sum(int... args)
, sum(double... args)
, signature sum(int... args)
more specific because invocation of method passed on sum(double... args)
applying widening conversion. same not hold sum(boolean... args)
method, cannot converted.
java language specification, se 8 version:
15.12. method invocation expressions
15.12.2.5. choosing specific method
the java programming language uses rule most specific method chosen.
...
one applicable method m1 more specific applicable method m2, invocation argument expressions e1, ..., ek, if of following true:
...
- m2 not generic, , m1 , m2 applicable strict or loose invocation, , m1 has formal parameter types s1, ..., sn , m2 has formal parameter types t1, ..., tn, type si more specific ti argument ei (1 ≤ ≤ n, n = k).
...
a type s more specific type t expression if s <: t (§4.10).
4.10. subtyping
4.10.1. subtyping among primitive types
double >1 float
float >1 long
long >1 int
Comments
Post a Comment