Java 使用三元运算符“什么都不做”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30856260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:16:02  来源:igfitidea点击:

"Do nothing" using ternary operator

javaandroid

提问by domi

I want to use the ternary operator like this - checking only the truepart of the statement:

我想像这样使用三元运算符 - 只检查true语句的一部分:

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:

是否可以排除此语句的“else”部分的逻辑?我尝试使用return;但编译器给出了错误。基本上我想要实现的是使用三元运算符的语句,如下所示:

foo() ? bar();

Is this achievable?

这是可以实现的吗?

采纳答案by wvdz

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 构造:

if (foo())
    bar();

回答by A.v

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.

如果它像那样工作,我们就不会再称它为三元了。我认为唯一的方法是做一些什么都不做的事情。例如调用一个具有空主体的方法,或者如果您将此操作的值分配给变量,则只需分配一个默认值。