Lambda参数 [英] Lambda Parameters

查看:175
本文介绍了Lambda参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解方法参考的语法,其中有两个参数 a& b ,并且引用是 a 在 b 上的方法。

I am having trouble understanding the syntax for a method reference, where there are two parameters
a & b, and the reference is to a method ofaonb.

例如
我理解how
Arrays.sort(personArray,comparatorators: compareByName);

等同于

Arrays.sort(personArray,(o1,o2) - > comparatorators.compareByName(o1,o2 ));

,因为在这种情况下,lambda参数匹配方法调用参数(o1,o2)

这个问题的方法λÚ
stream.sorted((o1,o2) - > o1.compareToIgnoreCase(o2) );

我的IDE告诉我,相当于:

stream.sorted(String :: compareToIgnoreCase);

,我找不到替换该语法的规则: a.method(b)

Howevever for this lambda
stream.sorted((o1, o2) -> o1.compareToIgnoreCase(o2));
my IDE tells me that is equivalent to:
stream.sorted(String::compareToIgnoreCase);
and I am not finding a rule for replacing that syntax: a.method(b)with a method reference.

例如,如果lambda有三个或更多参数怎么办?这是合法吗?第一个参数是否成为方法目标,其余的参数成为参数?

For example, what if there are three or more parameters to the lambda? Is that legal? Does the first parameter become the method target, and the remaining become the parameters?

推荐答案

我认为你在寻找 JLS第15.13.3 页,其中包括:

I think you're looking for JLS section 15.13.3, which includes:


如果表单是 ReferenceType :: [TypeArguments] Identifier ,调用方法的主体类似地具有编译时声明的方法调用表达式的效果,编译时声明是方法引用表达式的编译时声明。方法调用表达式的运行时评估如第15.12.4.3节,第15.12.4.4节和第15.12.4.5节中所述,其中:

If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:


  • 调用模式是从§15.12.3中指定的编译时声明派生的。

  • The invocation mode is derived from the compile-time declaration as specified in §15.12.3.

如果编译时声明一个实例方法,则目标引用是调用方法的第一个形式参数。

If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

如果编译时声明是一个实例方法,那么方法调用表达式调用方法的第二个和后续形式参数。否则,方法调用表达式的参数是调用方法的形式参数。

If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.

基本上注意最后两个项目符号。

Note the last two bullets, basically.


例如,如果有三个或更多参数?这是合法吗?第一个参数是否成为方法目标,其余参数成为参数?

For example, what if there are three or more parameters to the lambda? Is that legal? Does the first parameter become the method target, and the remaining become the parameters?

Yup:)

这篇关于Lambda参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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