Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a lambda function that cannot be a method reference

in a lecture I gave at my company I suggested converting any complex lambda to a method reference (more readable and better debug and testing) and was asked if it is always possible.

I searched and could not find a lambda that cannot be replaced with method reference.

am I right? (lambda can always be replaced with method reference)

like image 675
Tal Joffe Avatar asked Feb 16 '16 21:02

Tal Joffe


People also ask

Is lambda a method reference?

Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects.

Can we replace lambda expression with method reference?

The method references can only be used to replace a single method of the lambda expression.

Are there any differences between lambda expressions and method references?

Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it.

Is method reference better than lambda?

Lambdas are clearer The method reference syntax could stand in for either one. It hides what your code is actually doing.


1 Answers

Method reference cannot capture variables. So a capturing lambda cannot be directly converted to a method reference. For example,

int x = 1;
numbers.replaceAll(n -> n + x);

In some cases, if only one variable is captured, it might be possible to convert lambda to a method reference on the captured variable. For example,

String greeting = "Hello, ";

people.replaceAll(name -> greeting + name);

Can be converted to method reference as

people.replaceAll(greeting::concat);
like image 121
Misha Avatar answered Nov 14 '22 22:11

Misha