繁体   English   中英

Java泛型泛型类型参数和Optionals的奇怪编译错误

[英]Java weird compilation error with raw generic type parameter and Optionals

以下Java代码无法编译(使用javac 1.8.0_121

import java.util.Optional;

class B<T> {}

public class Test {
    static B<Integer> f1(B<Object> a) { return null; }

    static B<Integer> f2() {
       Optional<B> opt = Optional.empty(); // note the raw type B
       return opt.map(Test::f1).get();
       // error: incompatible types: Object cannot be converted to B<Integer>
    }
}

我的问题是:为什么代码不能像上面那样编译,如果我改变f1来获取原始类型,为什么它会编译:

static B<Integer> f1(B a) { return null; } // program compiles with raw B

我的猜测是opt.map被推断为返回Optional<Object> (而不是Optional<B<Integer>> ),但为什么呢? 我已经查看了泛型和类型擦除(JLS 4.8)的其他问题,但它们都处理了在原始类型本身上调用方法时的情况(例如, )。 这里, opt不是原始的,它只需要一个原始类型参数。 另外,为什么第二个版本(参数a是原始B而不是B<Object> )有效?

编译错误消息

Error java: incompatible types: java.lang.Object cannot be converted to B<java.lang.Integer>

让f1使用? extends Object ? extends Object ,向B添加通配符类型。

import java.util.Optional;

class B<T> {}

public class Test {
   static B<Integer> f1(B<? extends Object> a) { return null; }

   static B<Integer> f2() {
       Optional<B<?>> opt = Optional.empty(); // note the raw type B
       return opt.map(x -> f1(x)).get();
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM