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.
A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter).
A method reference can also be applicable to constructors in Java 8. A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor.
Argument Names When you declare an argument to a method or a constructor, you provide a name for that argument. This name is used within the method body to refer to the data. The name of an argument must be unique in its scope.
3. Java Default Constructor. If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With