variadic functions - Java 3 dots parameter (varargs) behavior when passed no arguments or null -
i tried , weird behavior java, can explain me?
boolean testnull(string... string) { if(string == null) { return true; } else { system.out.println(string.getclass()); return false; } } boolean calltestnull(string s) { return testnull(s); }
then have test case:
@test public void test_cases() { asserttrue(instance.testnull(null)); // null assertfalse(instance.testnull()); // not null assertfalse(instance.calltestnull(null)); // not null }
the question if call testnull()
directly parameter null
, true
back, if call calltestnull()
null
, calls testnull()
, tells me parameter not null, empty array.
the question if call testnull() directly parameter null, true back, if call calltestnull() null, calls testnull(), tells me parameter not null, empty array.
yes. if call argument compile-time type of string
, compiler knows can't string[]
, wraps within string array. this:
string x = null; testnull(x);
is equivalent to:
string x = null; testnull(new string[] { x });
at point, (misleadingly-named) string
parameter have non-null value - instead, refer array of size 1 sole element null reference.
however, when use null
literal directly in method call, that's directly convertible string[]
, no wrapping performed.
from jls section 15.12.4.2:
if method being invoked variable arity method m, has n > 0 formal parameters. final formal parameter of m has type t[] t, , m being invoked k ≥ 0 actual argument expressions.
if m being invoked k ≠ n actual argument expressions, or, if m being invoked k = n actual argument expressions and type of k'th argument expression not assignment compatible t[], argument list (e1, ..., en-1, en, ..., ek) evaluated if written (e1, ..., en-1, new |t[]| { en, ..., ek }), |t[]| denotes erasure (§4.6) of t[].
(emphasis mine.)
the bit i've emphasized why wrapping only happens when compile-time type of argument string
, not null type.
Comments
Post a Comment