在 Java 中传递 lambda 表达式时,方法不明确
让我们有一个功能接口(为了简洁起见,我省略了实现并简化了情况):Functional
@FunctionalInterface
public interface Functional<E> {
void perform(E e);
default <T extends Number> void method(E e, T t) { }
default <T extends Number> void method(E e, Function<E, T> function) { }
}
还有一段简单的代码:
Functional<String> functional = (string) -> {};
functional.method("string", (string) -> 1);
为什么由于 lambda 作为参数传递,因此该方法不明确?这应该很容易区分。method()
日食:
该方法对于类型是不明确的
method(String, Function<String,Integer>)
Functional<String>
这在IntelliJIdea上也是可重复的。
Javac输出(感谢@AndyTurner):
Main.java:21: error: reference to method is ambiguous
functional.method("string", (string) -> 1);
^
both method <T#1>method(E,T#1) in Functional and method <T#2>method(E,Function<E,T#2>) in Functional match
where T#1,E,T#2 are type-variables:
T#1 extends Number declared in method <T#1>method(E,T#1)
E extends Object declared in interface Functional
T#2 extends Number declared in method <T#2>method(E,Function<E,T#2>)
和
Main.java:21: error: incompatible types: cannot infer type-variable(s) T
functional.method("string", (string) -> 1);
^
(argument mismatch; Number is not a functional interface)
where T,E are type-variables:
T extends Number declared in method <T>method(E,T)
E extends Object declared in interface Functional
编辑:一个有趣的事实。当我用 替换时,它有效。似乎无法扩展,等等...default <T extends Number>
<T>
T
Number
Throwable
default <T> void method(E e, T t) { }
default <T> void method(E e, Function<E, T> function) { }
编辑2:当我对接口声明进行泛型类型时,它也可以工作:T
@FunctionalInterface
public interface Functional<E, T extends Number> {
void get(E e);
default void method(E e, Function<E, T> function) { }
default void method(E e, T t) { }
}