java - 你能解释一下为什么第一个展开的方法引用不能编译吗?
问题描述
在这个例子中,传递一个方法引用Stream.of
是行不通的,但是一旦它被包装它就可以工作了。我不明白为什么会这样。方法引用不等同于功能接口吗?
public class A {
String a() {
return "";
}
void b() {
Stream.of(this::a); // won't compile
Stream.of(wrap(this::a)); // will compile
}
static <T> Supplier<T> wrap(Supplier<T> f) {
return f;
}
}
解决方案
Stream.of
具有以下签名:
public static<T> Stream<T> of(T t)
以下示例将编译,因为您明确提供了T
.
Stream<Supplier<String>> a = Stream.of(this::a);
第一个示例Stream.of(this::a);
相当于:
Object a = this::a;
whereObject
不是功能接口,不会编译。
提供一个功能接口,这个例子编译:
Runnable a = this::a;
Stream.of(a);
在第二个例子中,wrap
提供了一个功能接口Supplier
推荐阅读
- ios - Ionic 4.2.1 模态内存泄漏
- json - 特定字符串后 Hive 中的正则表达式
- python - 使用 HTTPS/URLLIB 和 Python 在给定站点 (Jalopnik) 上执行搜索
- sql - 使用 BCP 不断收到导入错误“字符串数据,右截断”
- python - 如何从另一个目录运行 Python pipenv?
- python - 子数组中元素的平均值
- php - 如何确保图像已在 Laravel 5 中正确提供?
- tomcat - nginx反向代理spring安全认证GET而不是POST
- javascript - 向已有参数的函数 prop 添加参数
- python - 计算嵌套列表中的所有元组元素