Java Varargs edge case confusion -
i little bit puzzled this:
void a(){ log.d(tag, "noargs"); } void a(int... s){ log.d(tag, "varargs"); }
my first question logged if phone call a();? please seek guess because trying illustrate confusion this. tested , reply in end of question.
the real question how varargs work, how jvm know method calling since way phone call them same?
also there in java (or planned) allow this
as3 code: function sayhello(somebody:string = “world”):void{} //this allows specify default values of arguments , have them optional
answer noargs ecipse references method.
the behaviour you're observing because java always chooses most specific version of overloaded method based on arguments pass (further reading).
given scenario:
void a() { log.d(tag, "noargs"); } void a(int... s) { log.d(tag, "varargs"); }
a phone call a()
matches void a() { ... }
method - it's most specific version of method given arguments. when remove void a() { ... }
varargs method becomes specific version , called instead.
you can take step further:
public class varargstest { public static void a(int... s) { system.out.println("int varargs invoked."); } public static void a(short... s) { system.out.println("short varargs invoked."); } public static void a(long... s) { system.out.println("long varargs invoked."); } public static void a(byte... s) { system.out.println("byte varargs invoked."); } public static void main(string... args) { a(); } }
this invokes byte...
overload of a
. if remove that, short...
version gets called, int...
, long...
.
if instead add together overload char...
argument, becomes compilation error because char
, byte
have same specificity - compiler unable determine version right 1 phone call unless explicitly provide argument method call.
java varargs
No comments:
Post a Comment