Continuity8 Continuity8 - 11 months ago 35
Java Question

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

Java is littered with statements like:

if(cage.getChicken() != null) {
dinner = cage.getChicken();
else {
dinner = getFreeRangeChicken();

Which takes two calls to
before the returned object can be assigned to

This could also be written in one line like so:

dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();

But alas there are still two calls to

Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:

FutureMeal chicken = cage.getChicken();
dinner = chicken != null? chicken : getFreeRangeChicken();

So is there any way to say:

Variable var = some value if some value is not null OR some other

And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.

As this is such common code it'd be great to have a one-liner to write it.

Do any other languages have this feature?

Answer Source

Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.

You can use the result variable as your temporary, like this:

dinner = ((dinner = cage.getChicken()) != null?) dinner : getFreeRangeChicken();

This, however, is hard to read.