2
关于 Java 泛型方法定义的疑惑
source link: https://www.v2ex.com/t/859220
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在 https://www.v2ex.com/t/858692 里讨论了 "? super T 和 ? extends T" 的问题。我现在有一个疑惑,在设计接口的时候,应该如何正确使用泛型通配符。
借用引用该回答里的定义,有 3 个类:A1 、A2 、A3 ,A2 继承 A1 ,A3 继承 A2 ,那么有:A1>A2>A3 。如果想设计一个工具方法,接收所有继承自 A1 的元素,以及一个对元素操作的方法。理论上可以这个写:
interface Util {
void process(List<? extends A1> list, Function<? extends A1, Boolean> function);
}
但是实际上使用的时候,下面代码会报错:
Util util = (l, f) -> {
l.forEach(e -> {
f.apply(e); // 这里会报错
});
};
在报错的地方,IDE 提示如下:
Required type:
capture of ? extends A1
Provided:
capture of ? extends A1
这里该如何理解呢?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK