Writing a lambda expression when parameters are ignored in the body

前端 未结 1 1409
抹茶落季
抹茶落季 2020-12-10 23:34

How do I write a lambda expression if it doesn\'t require arguments and hence its name is excessive?

This way doesn\'t compile:

setRowFactory(-> n         


        
相关标签:
1条回答
  • 2020-12-11 00:26

    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.

    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 Specification defines the syntax of a lambda expression

    LambdaExpression:
      LambdaParameters -> LambdaBody 
    

    and

    LambdaParameters:
      Identifier
      ( [FormalParameterList] )
      ( InferredFormalParameterList )
    InferredFormalParameterList:
      Identifier {, Identifier}
    

    In other words, you cannot omit an identifier.


    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.

    0 讨论(0)
提交回复
热议问题