4 ms·
Here's an even shorter one-liner: return nullableVariable != null && nullableVariable.someMethodCall() ? true : fallbackIfNullMethodCall();
by Hermel 7y ago
Here's an even shorter one-liner:
return nullableVariable != null && nullableVariable.someMethodCall() ? true : fallbackIfNullMethodCall();
- mormegil 7y ago"? true :" is equivalent to just "||".
- thomasahle 7y agoAnd "X && Y || Z" is usually equivalent to "X ? Y : Z". So "nullableVariable != null ? nullableVariable.someMethodCall() : fallbackIfNullMethodCall();".
- twiceaday 7y agoIf X is true and Y is false this returns Y instead of Z which is wrong.
- jeroenhd 7y agoThis works in this case, but the pattern is less easy when the result is not a boolean. But I agree, in this specific case using a ternary operator after a null check is probably easier.