Using a constructor reference where the constructor has a non-empty list of parameters

Considering..

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 a method reference."

I know the Foo::new syntax for the no-arg constructor, but I don’t see how I could pass foo as an argument. Of course, I missed something.

+5
source share
1 answer

I know the Foo::new syntax for the no-arg constructor

This is not what Foo::new does. This expression will expand to what is necessary in the context that he used.

In this case

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

will look for the constructor that needs the Foo argument.

+8
source

Source: https://habr.com/ru/post/1246909/


All Articles