三元运算符

新手上路,请多包涵

是否有可能改变这个:

 if (string != null) {
    callFunction(parameters);
} else {
    // Intentionally left blank
}

到三元运算符?

原文由 Lucas Pugliese 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 363
1 个回答

好吧,Java 中的 ternary operator 就像这样……

 return_value = (true-false condition) ? (if true expression) : (if false expression);

…另一种看待它的方式…

 return_value = (true-false condition)
             ? (if true expression)
             : (if false expression);


您的问题有点含糊,我们必须在这里假设。

  • If (and only if) callFunction(...) declares a non-void return value ( Object , String , int , double 等..) - 它似乎没有通过你的代码做到这一点 - 那么你可以这样做……
   return_value = (string != null)
               ? (callFunction(...))
               : (null);

  • 如果 callFunction(...) 没有返回值,那么你 就不能 使用三元运算符!就那么简单。您将使用不需要的东西。

    • 请发布更多代码以解决任何问题

尽管如此, 三元运算符应该只代表替代赋值!! 您的代码似乎没有这样做,所以您不应该那样做。

这就是他们应该如何工作……

 if (obj != null) {            // If-else statement

    retVal = obj.getValue();  // One alternative assignment for retVal

} else {

    retVal = "";              // Second alternative assignment for retVale

}

这可以转换为…

 retVal = (obj != null)
       ? (obj.getValue())
       : ("");


由于看起来您 可能 只是想将此代码重构为单行代码,因此我添加了以下内容

另外,如果你的虚假条款真的是空的,那么你可以这样做……

 if (string != null) {

    callFunction(...);

} // Take note that there is not false clause because it isn't needed

或者

if (string != null) callFunction(...);  // One-liner

原文由 Christopher Rucinski 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题