is there a lambda function that cannot be a method reference

那年仲夏 提交于 2019-12-07 05:21:10

问题


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)


回答1:


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);


来源:https://stackoverflow.com/questions/35443655/is-there-a-lambda-function-that-cannot-be-a-method-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!