在下面的类中,两个方法的返回类型与三元运算符的思路不一致:
return condition?a:b;
相当于
if(condition) {
return a;
} else{
return b;
}
第一个返回 Double,第二个返回 Long:
public class IfTest {
public static Long longValue = 1l;
public static Double doubleValue = null;
public static void main(String[] args) {
System.out.println(getWithIf().getClass());// outpus Long
System.out.println(getWithQuestionMark().getClass());// outputs Double
}
public static Object getWithQuestionMark() {
return doubleValue == null ? longValue : doubleValue;
}
public static Object getWithIf() {
if (doubleValue == null) {
return longValue;
} else {
return doubleValue;
}
}
}
我可以想象这与编译器窄转换 getWithQuestionMark()
的返回类型有关,但这种语言明智吗?这肯定不是我所期望的。
欢迎任何见解!
编辑:下面有很好的答案。此外,@sakthisundar 引用的以下问题探讨了三元运算符中类型提升的另一个副作用:Tricky ternary operator in Java - autoboxing
最佳答案
基本上是遵循section 15.25 of the JLS的规则,具体来说:
Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
[...]
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
所以 section 5.6.2紧随其后,这基本上涉及拆箱 - 所以这使您的表达式工作就像 longValue
和 doubleValue
是类型 long
和 double
分别对 long
应用加宽提升以获得 double
的整体结果类型。
然后将 double
装箱以便从该方法返回一个 Object
。
关于java - "Wrong"在 Java 中使用 if 与三元运算符时的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12108998/