java 在主体中忽略参数时编写 lambda 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37597728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a lambda expression when parameters are ignored in the body
提问by Dims
How do I write a lambda expression if it doesn't require arguments and hence its name is excessive?
如果 lambda 表达式不需要参数,因此它的名称过多,我该如何编写它?
This way doesn't compile:
这种方式不编译:
setRowFactory(-> new TableRowCustom());
But this one does:
但这个确实:
setRowFactory(__ -> new TableRowCustom());
Is there a better way?
有没有更好的办法?
回答by Sotirios Delimanolis
Since you've mentioned that this works
既然你提到这有效
setRowFactory(__ -> new TableRowCustom());
I assume that the expected functional interface method must accept a single argument. The identifier _
is a reserved keyword since Java 8.
我假设预期的功能接口方法必须接受单个参数。标识符_
是自 Java 8 以来的保留关键字。
I would just use a throwaway single (valid identifier) character.
我只会使用一次性的单个(有效标识符)字符。
setRowFactory(i -> new TableRowCustom());
setRowFactory($ -> new TableRowCustom()); // allowed, but avoid this
or even
甚至
setRowFactory(ignored -> new TableRowCustom());
to be explicit.
要明确。
The Java Language Specificationdefines the syntax of a lambda expression
在Java语言规范定义了一个lambda表达式的句法
LambdaExpression:
LambdaParameters -> LambdaBody
and
和
LambdaParameters:
Identifier
( [FormalParameterList] )
( InferredFormalParameterList )
InferredFormalParameterList:
Identifier {, Identifier}
In other words, you cannot omit an identifier.
换句话说,您不能省略标识符。
As Holgersuggests, if and when they decide to use _
as an unused parameter name, it will be easy to change from __
to _
in your source code. You may want to just stick with that for now.
作为霍尔格建议,如果当他们决定使用_
作为一个未使用的参数名称,它会很容易从改变__
到_
你的源代码。您现在可能只想坚持下去。