java - Check if returned value is not null and if so assign it, in one line, with one method call -



java - Check if returned value is not null and if so assign it, in one line, with one method call -

java littered statements like:

if(cage.getchicken() != null) { dinner = cage.getchicken(); else { dinner = getfreerangechicken(); }

which takes 2 calls getchicken() before returned object can assigned dinner.

this written in 1 line so:

dinner = cage.getchicken() != null? cage.getchicken() : getfreerangechicken();

but alas there still 2 calls getchicken().

of course of study assign local variable utilize ternary operator 1 time again assign if not null, 2 lines , not pretty:

futuremeal chicken = cage.getchicken(); dinner = chicken != null? chicken : getfreerangechicken();

so there way say:

variable var = value if value not null or other value;

and guess i'm talking syntax here, after code compiled doesn't create much difference how code written in performance sense.

as such mutual code it'd great have one-liner write it.

do other languages have feature?

java lacks coalesce operator, code explicit temporary best selection assignment single call.

you can utilize result variable temporary, this:

dinner = ((dinner = cage.getchicken()) != null?) dinner : getfreerangechicken();

this, however, hard read.

java syntax null variable-assignment method-call

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -