Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 594
Sean Connolly Avatar asked Apr 12 '16 04:04

Sean Connolly


People also ask

Which constructor has an empty parameter list?

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).

What is constructor reference in Java?

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.

When declaring a parameter to a method or a constructor this is provided for that parameter?

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.

Which one is the default constructor of the following Java class when no constructor is provided?

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.


1 Answers

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.

like image 135
Savior Avatar answered Oct 11 '22 16:10

Savior