If you put the cursor on a bound-receiver method reference such as str::toUpperCase
in IntelliJ IDEA and press Alt+Enter, it offers to replace it with a lambda. If you go ahead, it changes the method reference to () -> str.toUpperCase()
. This is probably a bug in IntelliJ IDEA, though I suspect it's a common bug in other IDEs too. Why? Well, it's not always equivalent. Take the following little puzzle. What is the output of the following code?
import java.util.function.Supplier;
public class Scratch {
private static String str;
public static void main(String[] args) {
str = "a";
Supplier<String> methodref = str::toUpperCase;
Supplier<String> lambda = () -> str.toUpperCase();
str = "b";
System.out.println(methref.get());
System.out.println(lambda.get());
}
}
This code shows that the method reference and the lambda are not equivalent. The code prints different values on each line: "a" and "b". My question is: what is the correct lambda equivalent of this type of method reference?