y07k2 y07k2 - 7 months ago 30
Java Question

"?:" instead of "if else" statement with Boolean not always working

Why this

isWorldRanking ? sIsWorldAdapterInitiated = true : sIsCountryAdapterInitiated = true;

is not working (with error
Variable expected
)? Works only when I use
if else

E.g. this:

otherList.get(i).setFollowersCountry(isFavorite ? otherList.get(i).getFollowersCountry() + 1 : otherList.get(i).getFollowersCountry() - 1);

and this:

List<FamousTop40Ranking> otherList = mIsWorldRanking ? sCountryFamousModelList : sWorldFamousModelList;

are working :)

Of course
Boolean isWorldRanking, isFavorite

Can you help?


extending the answer given by Konstantin Yovko

consider the usuage of ? with : for assiging value to a variable as below.

variable_of_type_T = boolean_condition ? value1_of_type_T : value2_of_type_T

values may be direct constant values or may be output of a method or an expression. Clearly a void method or any expression having no output is of no use as in that case we will not be able to assign any value.