首页 > 解决方案 > 你能解释一下为什么第一个展开的方法引用不能编译吗?

问题描述

在这个例子中,传递一个方法引用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;
    }
}

标签: javajava-8java-streammethod-reference

解决方案


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


推荐阅读