Is there a lambda function that cannot be a method reference

in the lecture that I gave at my company, I suggested converting any complex lambda into a method link (more readable and better debugging and testing), and the question was asked whether this is always possible.

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

I'm right? (lambda can always be replaced with a reference to a method)

+5
source share
1 answer

A method reference cannot capture variables. Thus, an exciting lambda cannot be directly converted to a method reference. For instance,

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

In some cases, if only one variable is fixed, it may be possible to convert the lambda to a method reference to the captured variable. For instance,

 String greeting = "Hello, "; people.replaceAll(name -> greeting + name); 

Can be converted to a method reference as

 people.replaceAll(greeting::concat); 
+10
source

Source: https://habr.com/ru/post/1243178/


All Articles