Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I replace if statement with conditional operator (?:)?

I've been struggling to turn

private PlaneClass preferredClass;

if (preferredClass == PlaneClass.FIRST_CLASS)
    preferredClass = PlaneClass.ECONOMY_CLASS;
else
    preferredClass = PlaneClass.FIRST_CLASS;

into

preferredClass == PlaneClass.FIRST_CLASS ? 
                preferredClass = PlaneClass.ECONOMY_CLASS 
                               : preferredClass = PlaneClass.FIRST_CLASS;

The if-statement compiles. The conditional operator doesn't. (Error messages: 1. Type mismatch: cannot convert from PlaneClass to boolean 2. syntax error on token "=". And two other error...). Where did I go wrong?

like image 924
enhancedJack Avatar asked Aug 28 '26 02:08

enhancedJack


1 Answers

The syntax is:

condition ? value1 : value2;

not

condition ? statement1 : statement2;

The conditional operator is an expression, not a statement. It doesn't execute statements like an if statement does: it returns a value.

What you mean is:

preferredClass = (preferredClass == PlaneClass.FIRST_CLASS ? 
            PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS);
like image 134
khelwood Avatar answered Aug 30 '26 15:08

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!