本文介绍了使用三元运算符(`?)时,Java是否无法推断出泛型类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器能够确定分配,但不分配给三元运算符(?)?

Why is the compiler able to determine the generic type parameter for anassignment, but not for the ternary operator (?)?

我对编译器能否推断出通用类型有疑问如果是直接"分配,则参数,但如果是三元分配,则参数失败运算符(?).我的示例使用番石榴的 Optional 类来说明我的观点,但是我认为根本问题是普遍的,并不局限于 Optional .

I have a question regarding the compiler being able to deduce the generic typeparameter in case of a "direct" assignment but failing in case of the ternaryoperator (?). My examples uses Guava's Optional class, to make my point, butI think the underlying issue is generic and not restricted to Optional.

Optional 具有通用功能 absent():

public static <T> Optional<T> absent();

,然后我可以将 Optional< T> 分配给 Optional< Double> :

and I can assign an Optional<T> to an Optional<Double>:

// no compiler error
final Optional<Double> o1 = Optional.absent();

编译器如何实现,在这种情况下, T 应该是 Double .因为当使用三元运算符(?)时,我需要专门告诉编译器给我们 Integer 作为通用参数

How does the compiler realize, that T should be Double in this case. Becausewhen using the ternary operator (?), I need to tell the compiler specificallyto us Integer as the generic parameter

// Type mismatch: cannot convert from Optional<capture#1-of ? extends Object> to Optional<Integer>
final Optional<Integer> o2 = true
    ? Optional.of(42)
    : Optional.<Integer>absent();

否则我会收到以下错误

为什么直接"分配与使用三元分配之间有区别操作员?还是我想念其他东西?

Why is there a difference between a "direct" assignement and using the ternaryoperator? Or is there something else I am missing?

推荐答案

由于类型推断规则,似乎三元表达式不能从返回类型推断类型参数.三元表达式的类型取决于其操作数的类型.但是其中一个操作数具有不确定的类型参数( Optional.absent()).此时三元表达式仍然没有类型,因此它不会影响类型参数.

Because of type inference rules, it appears the ternary expression does not infer the type parameter from the return type. The type of the ternary expression depends on the types of its operands. But one of the operands has undetermined type parameter (Optional.absent()). At that point the ternary expression still does not have a type, so it cannot influence the type parameter.

您也可以查看此错误报告以了解更多信息.您可以查看 JLS .

You can also look into this bug report for more information. You can look into the JLS .

JLS 所说的内容:

这篇关于使用三元运算符(`?)时,Java是否无法推断出泛型类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:34