Reputation: 39
x>5 ? list1.add(something) : list2.add(something);
Why do I have to take the return value from expressions of ternary operator? I should have the option to ignore the return value.
It's forcing me to take the return value like below
boolean y = x>5 ? list1.add(something) : list2.add(something);
Upvotes: 0
Views: 925
Reputation: 18430
Because the conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
It does not execute because it's an expression not a statement.
Upvotes: 0
Reputation: 140319
The conditional ?:
operator produces an expression (which means it's a bit of the syntax tree which has a value when it is executed). However, it's not a statement expression, meaning you can't just add a ;
to the end of it to make a statement.
Examples of statement expressions are method invocations, constructor invocations, pre/post-increments. These make sense to stand by themselves as a statement, because they have (or can have) side effects. You can take the expression i++
, add a semicolon i++;
, and you have a valid, meaningful statement.
Non-statement expressions like addition 1 + 2
don't make sense by themselves. It's a bit like saying "cat and dog": it's not a "whole sentence". A conditional operator makes something like "if rain then cat else dog", which doesn't make much sense either.
If you find yourself wanting to write a conditional expression as a statement, just use an if/else statement instead.
Upvotes: 2
Reputation: 59104
The conditional operator is part of an expression, which means its purpose is to be evaluated. If you're not trying to get a value you shouldn't be using the conditional operator. That's what if
statements are for.
Though in this case, it looks like you could achieve the effect you want using:
(x > 5 ? list1 : list2).add(something);
Upvotes: 2
Reputation: 27119
For the same reason you can't do 1 + 1;
on its own: because an expression by itself is not a statement (as the actual error message tells you).
Upvotes: 3