[英]Assign to a reference of a more generic type
有什么辦法可以使用如下更通用的類型引用this :: method?
Number method(Integer input){ return 1;}
void test(){
Function<Integer, Number> ref = this::method; //OK
Function<Number, Number> moreGenericRef = this::method // does not compile.
Function<? extends Number, Number> moreGenericRef2 = this::method // does not compile.
}
我希望能夠做到以下幾點。
Map<String, Function<Number,Number>> maps;
maps.add("method1", this::method)
maps.add("method2", this::method2)
maps.get("methods1").apply(1.2);
maps.get("methods2").apply(1);
這些函數是適配器,Stream <Number>的映射器將調用這些適配器。
好吧,如果您將定義更改為:
Function<? extends Integer, ? extends Number> moreGenericRef2 = this::method;
要么
Function<Integer, ? extends Number> moreGenericRef2 = this::method;
要么
Function<Integer, Number> moreGenericRef2 = this::method;
但是有諸如這樣的定義? extends Integer
? extends Integer
(其中Integer
是最終類毫無意義)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.