Memra

Method references: the four kinds

Shorthand for lambdas that just call a method — and how each kind maps.

Method references: a cleaner lambda spelling

When a lambda does nothing but call a single method, a method reference (::) makes the intent clearer. There are exactly four kinds:

| Kind | Syntax | Equivalent lambda | |---|---|---| | Static | Integer::parseInt | s -> Integer.parseInt(s) | | Bound instance | System.out::println | s -> System.out.println(s) | | Unbound instance | String::toUpperCase | s -> s.toUpperCase() | | Constructor | ArrayList::new | () -> new ArrayList<>() |

Static — the class provides a static method; all parameters come from the lambda:

Function<String, Integer> parse = Integer::parseInt;

Bound instance — a specific *object* is bound at the reference site; its method is called with the remaining parameters:

Consumer<String> print = System.out::println;  // out is the bound receiver

Unbound instance — no receiver is bound; the *first* lambda parameter becomes the receiver:

Function<String, String> upper = String::toUpperCase;
// equivalent: s -> s.toUpperCase()

Constructor::new creates a new instance with the remaining parameters:

Supplier<ArrayList<String>> factory = ArrayList::new;

The compiler matches the method reference to the functional interface's single abstract method by parameter and return types.

NORMAL ~/memra/learn/java-from-zero/method-references utf-8 LF