给出..

List<Foo> copy(List<Foo> foos) {
    return foos
            .stream()
            .map(foo -> new Foo(foo))
            .collect(Collectors.toList());
}

IntelliJ IDEA 2016.1.1报告说new Foo(foo)“可以用方法引用替换”。

我知道no-arg构造函数的Foo::new语法,但是看不到如何将foo作为参数传递。我肯定在这里错过了一些东西。

最佳答案



那不是Foo::new所做的。 This expression will expand to what is needed in the context it's used.

在这种情况下

List<Foo> copy(List<Foo> foos) {
    return foos.stream().map(Foo::new).collect(Collectors.toList());
}

会寻找需要Foo参数的构造函数。

关于java - 在构造函数具有非空参数列表的情况下使用构造函数引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36563400/

10-11 04:14
查看更多