是否可以更改这个:
if (string != null) {
callFunction(parameters);
} else {
// Intentionally left blank
}
转换为三元运算符吗?
是否可以更改这个:
if (string != null) {
callFunction(parameters);
} else {
// Intentionally left blank
}
转换为三元运算符吗?
嗯,Java中的三元运算符
的作用如下...
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
, etc..) - it seems like it does not do that via your code - then you could do this...
return_value = (string != null)
? (callFunction(...))
: (null);
If callFunction(...)
does not return a value, then you cannot use the ternary operator! Simple as that. You will be using something that you don't need.
然而,三元运算符应该仅表示替代赋值!
您的代码似乎并非如此,因此您不应该这样做。
以下是它们应该工作的方式...
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
Object dummy=condition? callFunction(parameters): null;
但是,与仅仅说 if(condition) callFunction(parameters);
相比,并没有任何优势。如果返回值是一个原始类型,则可能会增加不必要的开销,因为它将执行自动装箱。
Java 8 中有一种解决这个谜题的方法,即使对于 void
方法也适用:
((Runnable)(condition? ()->callFunction(parameters): ()->{})).run();
if
语句更具优势。可以。在else
块中保持相同的null
即可。
String result = str !=null ? callFunction(parameters) : null;
callFunction(parameters)
返回一个 String
。String
返回类型?问题的代码并不支持这样的结论。 - Holgerif
语句用于执行操作,三元运算符用于计算值。 - William F. JamesoncallFunction()
有返回类型,那么这是可能的。你可以像 SURESH ATTA 在他的回答中写的那样做:String result = str!=null ? callFunction(str) : null;
或者使用任何其他类型的结果或任何其他参数。如果您想在 else
语句中调用一个方法,这个方法需要与您 if
语句中的方法具有相同的返回类型。
如果您的方法没有返回类型/ callFunction()
的返回类型为 void
,则无法将您的 if
-else
语句更改为三元运算符。