Use of constructor reference where constructor has a non-empty parameter list

谁说胖子不能爱 提交于 2021-02-19 02:09:23

问题


Given..

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

IntelliJ IDEA 2016.1.1 reports that new Foo(foo) "can be replaced with method reference".

I'm aware of the Foo::new syntax for the no-arg constructor, but don't see how I could pass foo in as an argument. I'm surely missing something here.


回答1:


I'm aware of the Foo::new syntax for the no-arg constructor

That's not what Foo::new does. This expression will expand to what is needed in the context it's used.

In this case

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

would look for a constructor that needed a Foo argument.



来源:https://stackoverflow.com/questions/36563400/use-of-constructor-reference-where-constructor-has-a-non-empty-parameter-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!