问题
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