在Java中使用if与三元opertator时,"错误"返回类型

Miq*_*uel 17 java if-statement return ternary-operator

在下面的类中,两种方法的返回类型与三元运算符的思想不一致:

return condition?a:b;
Run Code Online (Sandbox Code Playgroud)

相当于

if(condition) {
    return a;
} else{ 
    return b;
}
Run Code Online (Sandbox Code Playgroud)

第一个返回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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以想象这与编译器缩小转换类型有关,getWithQuestionMark()但是语言明智吗?这肯定不是我所期望的.

任何见解都是最受欢迎的!

编辑:下面有很好的答案.此外,@ sakthisundar引用的以下问题探讨了三元运算符中出现的类型提升的另一个副作用:Java中的Tricky三元运算符 - 自动装箱

Jon*_*eet 14

基本上它遵循JLS第15.25节的规则,具体来说:

否则,如果第二个和第三个操作数具有可转换(第5.1.8节)到数字类型的类型,则有几种情况:

  • [...]

  • 否则,二进制数字提升(第5.6.2节)将应用于操作数类型,条件表达式的类型是第二个和第三个操作数的提升类型.

所以,第5.6.2节之后,这将主要涉及拆箱-所以这使得你的工作表现,就好像longValuedoubleValue人的类型longdouble分别和拓宽推广应用到long获得的总体结果类型double.

double是那么为了返回一个盒装Object的方法.

  • 啊哈!所以,`1 + 2`给出一个整数,`1 + 2d`给出一个double,同样```如果可能的话进行数字提升.仍然不是我所期望的,但比它与返回类型有任何关系更好.谢谢! (2认同)