java - "Wrong"在 Java 中使用 if 与三元运算符时的返回类型

标签 java if-statement return ternary-operator

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

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紧随其后,这基本上涉及拆箱 - 所以这使您的表达式工作就像 longValuedoubleValue 是类型 longdouble 分别对 long 应用加宽提升以获得 double 的整体结果类型。

然后将 double 装箱以便从该方法返回一个 Object

关于java - "Wrong"在 Java 中使用 if 与三元运算符时的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12108998/

相关文章:

java - 特殊字符问题 : MQ message PUT error : java. nio.charset.UnmappableCharacterException

c++ - (4 > y > 1) 是 C++ 中的有效语句吗?如果是,你如何评价?

javascript如何从参数函数中获取函数返回值

c++ - 函数中的 vector - 如何返回

java - 如何从文本文件中搜索名称

java - Mockito 模拟类返回 Null

java - 沉默 log4j

php - 根据值更改 td 类?

java - 对于 if-else 条件,哪一种更好的做法?

c - C 中如何返回 void* 指针?