为什么方法参考不适用于此?
Why method reference doesn't work with this?
我有一个类似这样的方法。
static <R> R applyOthers(Some some, Function<List<Other>, R> function) {
List<Other> others = ...;
return function.appply(others);
}
现在当我尝试这个时,
withSome(some -> {
List<Other> others1 = applyOthers(some, v -> v); // works
List<Other> others2 = applyOthers(some, Function::identity); // doesn't
});
一个错误,我明白了。
incompatible types: unexpected static method <T>identity() found in unbound lookup
where T is a type variable:
T extends Object declared in method <T>identity()
为什么 ::identity
不起作用?
Function<Object, Object> f1 = v1 -> v1;
Supplier<Object> s1 = Function::identity;
Supplier<Object> s2 = () -> Function.identity();
看到这段代码,我猜你只是误用了这里的方法引用。当我们说 SomeObject::method
时,此方法引用应与某些功能接口匹配。在上面的示例中,Function::identity
是一种供应商实例,而不是 java.util.function.Function
实例。
我们不应该说 Function::identity 是像 -
这样的 Function 的供应商吗
Supplier<Function<?,?>> a = Function::identity;
这就是它不起作用的原因?
如果我们替换“?”使用正确的类型 a.get() 有效。
我有一个类似这样的方法。
static <R> R applyOthers(Some some, Function<List<Other>, R> function) {
List<Other> others = ...;
return function.appply(others);
}
现在当我尝试这个时,
withSome(some -> {
List<Other> others1 = applyOthers(some, v -> v); // works
List<Other> others2 = applyOthers(some, Function::identity); // doesn't
});
一个错误,我明白了。
incompatible types: unexpected static method <T>identity() found in unbound lookup
where T is a type variable:
T extends Object declared in method <T>identity()
为什么 ::identity
不起作用?
Function<Object, Object> f1 = v1 -> v1;
Supplier<Object> s1 = Function::identity;
Supplier<Object> s2 = () -> Function.identity();
看到这段代码,我猜你只是误用了这里的方法引用。当我们说 SomeObject::method
时,此方法引用应与某些功能接口匹配。在上面的示例中,Function::identity
是一种供应商实例,而不是 java.util.function.Function
实例。
我们不应该说 Function::identity 是像 -
这样的 Function 的供应商吗Supplier<Function<?,?>> a = Function::identity;
这就是它不起作用的原因? 如果我们替换“?”使用正确的类型 a.get() 有效。