Using a conditional statement without assigning its result

Why do I need to assign the result of the following conditional expression to a variable to compile it?

piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));

The above does not compile as shown below:

boolean garbage = piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));

List#add()returns a boolean, but I would just ignore it. Is the conditional operator simply constructed in such a way that it needs to be assigned the values ​​returned from the functions, and the returning functions must be of the same type?

+3
source share
5 answers

From section 14.8 of JLS (expressions):

Some types of expressions can be used as operators, following them with a comma:

ExpressionStatement:
      StatementExpression ;

StatementExpression:
       Assignment
       PreIncrementExpression
       PreDecrementExpression
       PostIncrementExpression
       PostDecrementExpression
       MethodInvocation
       ClassInstanceCreationExpression

; , . , .

C ++ Java .

...

, , , void, . , (§15.26) (§14.4).

, - .

- , , , .

+5

(piece.isWhite() ? whitePieceSquares : blackPieceSquares).add(getSquare(pos));

: , , . , /.

boolean out = true;
(out ? System.out : System.err).println("Hello");
+4

C , -

void foo(int bar) {
    bar;
}

java , . , - , ... else..., :

(piece.isWhite() ? whitePieceSquares : blackPieceSquares).add(getSquare(pos));
+2

: , . ?:, .

+1

I assume your functions addreturn a boolean. Those who have to go somewhere, right?

0
source

Source: https://habr.com/ru/post/1785640/


All Articles