实例方法参考和 Lambda 参数 [英] Instance Method Reference and Lambda Parameters

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

问题描述

我无法理解方法引用的语法,其中有两个参数 ab,并且引用是对 a 的方法b 上.

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

例如我了解如何

Arrays.sort(personArray, comparators::compareByName);

相当于

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

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

because in that case the lambda parameters match the method call parameters (o1, o2).

但是对于这个 lambda

Howevever for this lambda

stream.sorted((o1, o2) -> o1.compareToIgnoreCase(o2));

我的 IDE 告诉我这相当于:

my IDE tells me that is equivalent to:

stream.sorted(String::compareToIgnoreCase);

而且我没有找到用方法引用替换该语法的规则:a.method(b).

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.

例如,如果 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?

是的:)

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

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