是否可以更改:
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);
你的问题有点模糊,我们必须在这里假设。
如果 (且仅当)
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
关于java - 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163713/