1

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?

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
  • 2
    Concerning the IntelliJ bug, it is only that it should indicate “_(may change semantics)_” like it does when performing it the other way around. You should report it. – Didier L Oct 16 '18 at 11:38

1 Answers1

1

For your Supplier setup, the answer is: There is no equivalent.

When you write:

str = "a";
Supplier<String> methodref = str::toUpperCase;

it literally becomes "a"::toUpperCase (that actually compiles).

Doe Johnson
  • 1,374
  • 13
  • 34