在主体中忽略参数时编写lambda表达式 [英] Writing a lambda expression when parameters are ignored in the body
问题描述
如果lambda表达式不需要参数,因此它的名称过多会怎么写?
How do I write a lambda expression if it doesn't require arguments and hence its name is excessive?
这种方式不能编译:
setRowFactory(-> new TableRowCustom());
但这个确实:
setRowFactory(__ -> new TableRowCustom());
有更好的方法吗?
推荐答案
因为你已经提到过这个有用了
Since you've mentioned that this works
setRowFactory(__ -> new TableRowCustom());
我假设预期的功能接口方法必须接受单个参数。 标识符 _
是自Java以来的保留关键字8.
I assume that the expected functional interface method must accept a single argument. The identifier _
is a reserved keyword since Java 8.
我只会使用一次性单(有效标识符)字符。
I would just use a throwaway single (valid identifier) character.
setRowFactory(i -> new TableRowCustom());
setRowFactory($ -> new TableRowCustom()); // allowed, but avoid this
甚至
setRowFactory(ignored -> new TableRowCustom());
要明确。
< a href =http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.1\"rel =noreferrer> Java语言规范定义lambda表达式的语法
The Java Language Specification defines the syntax of a lambda expression
LambdaExpression:
LambdaParameters -> LambdaBody
和
LambdaParameters:
Identifier
( [FormalParameterList] )
( InferredFormalParameterList )
InferredFormalParameterList:
Identifier {, Identifier}
换句话说,你不能省略标识符。
In other words, you cannot omit an identifier.
作为 Holger 建议,如果他们决定使用 _
作为未使用的参数名称,可以很容易地从<$ c $更改c> __ 到源代码中的 _
。你现在可能只想坚持下去。
As Holger suggests, 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.
这篇关于在主体中忽略参数时编写lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!