是否有一个lambda函数,不能作为方法引用 [英] is there a lambda function that cannot be a method reference

查看:135
本文介绍了是否有一个lambda函数,不能作为方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我给我公司的讲座中,我建议将任何复杂的lambda转换为方法参考(更易读,更好的调试和测试),并询问是否总是可行。

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.

我搜索过,无法找到一个无法用方法参考替换的lambda。

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

我是对的吗? (lambda总是可以用方法引用替换)

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

推荐答案

方法引用无法捕获变量。因此捕获lambda不能直接转换为方法引用。例如,

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

在某些情况下,如果只捕获一个变量,则可以将lambda转换为方法对捕获变量的引用。例如,

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

可以转换为方法参考

people.replaceAll(greeting::concat);

这篇关于是否有一个lambda函数,不能作为方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆