Java三元运算符对泛型类型推断的影响 [英] Java ternary operator influence on generics type inference

查看:424
本文介绍了Java三元运算符对泛型类型推断的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public List<String> foo1() {
    List<String> retval = bar();
    if (retval == null)
        return Collections.emptyList();
    else
        return retval;
}

public List<String> foo2() {
    List<String> retval = bar();
    return retval == null ? Collections.emptyList() : retval;
}

为什么 foo1()编译良好,而 foo2()有错误? (更精确地类型不匹配:不能从List< capture#1-of?extends Object>转换为List< String>

Why does foo1() compiles fine whereas foo2() has an error? (to be more precise "Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>")

我会认为这两个函数将编译为相同的字节码,所以一个聪明的编译器应该推断 emptyList() ...

I would have thought that both functions would compile to the same bytecode, so a clever compiler should infer the correct type for emptyList()...

推荐答案

在Java 8中为我编译。

Compiles for me fine in java 8.

早期版本的Java可能需要更多help

Earlier versions of Java might need more help

return retval == null ? Collections.<String>emptyList() : retval;

应该可以正常工作。

EDIT
这是因为Java 8类型推断的改进,如下所述

EDIT This is due to improvements in Java 8 type inference as explained here

http://openjdk.java.net/jeps/101

这里是一个包含亮点的博客: http://blog.jooq.org/ 2013/11/25 / a-less-known-java-8-feature-generalized-target-type-in​​ference /

And here's a blog with the highlights: http://blog.jooq.org/2013/11/25/a-lesser-known-java-8-feature-generalized-target-type-inference/

这篇关于Java三元运算符对泛型类型推断的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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