使用条件运算符而不分配其结果
为什么我必须将以下条件表达式的结果分配给变量才能编译?
piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));
上面的代码无法编译,下面的代码可以编译:
boolean garbage = piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));
List#add()
返回一个布尔值,但我会忽略它。难道条件运算符的设计方式是需要对函数返回的值进行赋值,并且这些返回函数必须具有相同的类型?
Why do I have to assign the result of the following conditional expression to a variable to get it to compile?
piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));
The above doesn't compile, the below does:
boolean garbage = piece.isWhite() ? whitePieceSquares.add(getSquare(pos)) : blackPieceSquares.add(getSquare(pos));
List#add()
returns a boolean, but I would just ignore that. Is it just that the conditional operator is designed in such a way that it's necessary to assign values returned from functions and those returning functions must have the same type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自 JLS 的第 14.8 节(表达式语句):
基本上,条件运算符的原则目标是评估其操作数 - 您将其用于副作用。
Peter Lawrey 的答案显示了更好的用法 - 您使用条件运算符来计算出将棋子添加到哪个方格,然后调用该方法。
From section 14.8 of the JLS (expression statements):
Basically, the principle aim of a conditional operator is to evaluate its operands - you're using it for the side-effects.
Peter Lawrey's answer shows a better use - you use the conditional operator to work out which square to add the piece to, and then you invoke the method on that.
尝试
编辑:不知道为什么有人怀疑这是一个有效的陈述。这是一个较短的示例,您应该能够编译/运行。
try
EDIT: Not sure why there is doubt this is a valid statement. Here is a shorter example which you should be able to compile/run.
在 C 中,这是可能的,因为你可以写类似的东西,
在 java 中,你不能,而且我不会错过它。但是,如果您出于某种原因不喜欢编写 if ... else ...,则应该编译:
In C, that would be possible, because you can write something like
In java, you can't, and I don't miss it. However, if you for some reason don't like writing if ... else ..., this should compile:
基本上答案是:只是因为。
?:
以及所有算术运算符只能出现在表达式的右侧。Basically the answer is: just because.
?:
and all the arithmetic operators can only appear on the right-hand side of an expression.我猜测您的
add
函数返回一个布尔值。那些人总得去某个地方,不是吗?I'm guessing that your
add
functions return a boolean. Those have to go somwhere, don't they?