8

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; 
1
  • 4
    a new String in upper case is still just a blank string, so s -> "" will do the same thing Commented Nov 21, 2018 at 12:49

2 Answers 2

16

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();
Sign up to request clarification or add additional context in comments.

Comments

5

There are four kinds of method references as shown below and your type falls in the second category, but UnaryOperator<String> essentially needs to represent a method which accepts any String argument and returns a String. However, the non-working method reference that you have used is actually working on a particular String object (i.e. not any String object)

enter image description here

Refer: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

3 Comments

Strictly speaking, new String()::toUpperCase is indeed a method reference, of the third kind (new String() is an object which has the toUpperCase method). It doesn't take arguments, but returns a String. It could be used as a Supplier<String>. But it is a very complicated way to say () -> "".
@glglgl Actually, the second type, right?
With 0-based counting even the 1st :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.