Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new" Keyword In Java Lambda Method Reference [duplicate]

I've seen a lot of methods where a new class is instantiated in a lambda method reference but can't seem to understand why. When is the new keyword needed in a method reference?

For example, the following passes compilation:

UnaryOperator<String>stringToUpperCase = String::toUpperCase;

But this doesn't:

UnaryOperator<String>stringToUpperCase = new String()::toUpperCase; 
like image 582
Clatty Cake Avatar asked Nov 21 '18 12:11

Clatty Cake


1 Answers

String::toUpperCase is a method reference that can be applied to any String instance.

new String()::toUpperCase is a method reference that can be applied to a specific String instance (the instance created by new String()).

Since UnaryOperator<String> expects a method that takes a String and returns a String, String::toUpperCase fits (since you can apply it on a String and get the upper case version of that String).

On the other hand, new String()::toUpperCase doesn't fit UnaryOperator<String>, since it is executed on an already specified String, so you can't pass another String instance to it.

It can, however, by assigned to a Supplier<String>, since it simply supplies an empty String instance:

Supplier<String> emptyStringToUpperCase = new String()::toUpperCase; 

This is similar to:

Supplier<String> emptyStringToUpperCase = () -> new String().toUpperCase();

while this:

UnaryOperator<String> stringToUpperCase = String::toUpperCase;

is similar to:

UnaryOperator<String> stringToUpperCase = s -> s.toUpperCase();
like image 73
Eran Avatar answered Oct 23 '22 09:10

Eran