"错误"在Java中使用if与三元opertator时的返回类型 [英] "Wrong" return type when using if vs. ternary opertator in Java

查看:156
本文介绍了"错误"在Java中使用if与三元opertator时的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the following class, the return type of the two methods is inconsistent with the idea that the ternary operator:

return condition?a:b;

相当于

if(condition) {
    return a;
} else{ 
    return b;
}

第一个返回一个Double,第二个返回Long:

The first returns a Double and the second a 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()的返回类型,但这种语言明智吗?这肯定不是我所期望的。

I can imagine this has to do with the compiler narrow casting the return type of getWithQuestionMark() but is that language wise ok? It's certainly not what I would have expected.

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

Any insights most welcome!

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

there's very good answers below. Additionally, the following question referenced by @sakthisundar explores another side effect of the type promotion occurring in the ternary operator: Tricky ternary operator in Java - autoboxing

推荐答案

基本上它遵循 JLS的第15.25节,具体为:

Basically it's following the rules of section 15.25 of the JLS, specifically:


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

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:


  • [...]

  • [...]

否则,二进制数字促销(第5.6.2节)适用于操作数类型,条件表达式的类型是第二和第三操作数的提升类型。

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.

所以第5.6节。跟随2 ,这基本上涉及拆箱 - 所以这使得你的表达式就好像 longValue doubleValue 分别为 long double 类型,并且扩展促销适用于 long 获取整体结果类型 double

So section 5.6.2 is followed, which will basically involves unboxing - so this makes your expression work as if longValue and doubleValue were of types long and double respectively, and the widening promotion is applied to the long to get an overall result type of double.

double 装箱,以便从该方法返回 Object

That double is then boxed in order to return an Object from the method.

这篇关于"错误"在Java中使用if与三元opertator时的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆