小编典典
好吧,ternary operatorJava中的行为就像这样……
return_value = (true-false condition) ? (if true expression) : (if false expression);
…另一种看待它的方式…
return_value = (true-false condition)
? (if true expression)
: (if false expression);
你的问题有点含糊,我们必须在这里假设。
如果(且仅当)callFunction(…)声明了一个non-void返回值(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
2020-03-18
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176332.html原文链接:https://javaforall.net
