Java 8 - Wildcard extends with BiPredicate not working
本问题已经有最佳答案,请猛点这里访问。
我不知道为什么它不起作用。
Eclipse中的错误消息:方法测试(水果,捕获1-of?bipredicate类型中的extends水果)不适用于参数(水果、芒果)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import java.util.function.BiPredicate; public class PredTest { public static void main(String[] args) { class Fruit { public String name; public String color; Fruit(String name) {this.name = name; } }; class Apple extends Fruit { Apple() {super("Apple");} }; class Mango extends Fruit { Mango() {super("Mango");} }; BiPredicate<Fruit, ? extends Fruit> tester = (f, nf) -> { System.out.println(nf.name); return true; }; Fruit f = new Fruit("Not named"); Apple a = new Apple(); Mango m = new Mango(); // ########### I see error in the below line System.out.println(tester.test(f, m)); } } |
假设您将lambda表达式更改为:
1 2 3 4 | BiPredicate<Fruit, ? extends Fruit> tester = (Fruit f, Apple nf) -> { System.out.println(nf.name); return true; }; |
您是否仍然希望编译器允许将一个
根据
将您的
1 2 3 4 | BiPredicate<Fruit, ? super Fruit> tester = (f, nf) -> { System.out.println(nf.name); return true; }; |
号
将消除编译错误。