I want to use the ternary operator like this - checking only the true
part of the statement:
foo() ? bar() : /* Do nothing */;
Is it possible to exclude the logic of the "else" part of this statement? I tried using return;
but the compiler gives the error. Basically all I want to achieve is a statement using ternary operator which would look like this:
foo() ? bar();
Is this achievable?
They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.
A ternary operator doesn't have a do nothing option for either the true or false path since the entire ternary command returns a value and so both paths must set a value. The “do nothing” value will depend on what value you want the ternary operator to return to indicate “do nothing”.
The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.
Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
The ternary operator is usually used to immediately assign a value.
String a = bar() ? foo() : null;
For your usecase, you can simply use an if construct:
if (foo()) bar();
If it would work like that we wouldn't call it ternary anymore. I think the only way is that do something which does nothing. for example call a method which has empty body, or if you assign a value from this operation to a variable just assign a default value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With