Search code examples
javalanguage-features

Java language spec: LambdaExpression in Java ConditionalExpression


In the Java 8 specification there is the following syntax description of the conditional operator ?: :

ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
ConditionalOrExpression ? Expression : LambdaExpression 

I understand the first two lines. But why is the third line necessary? What is so special about a LamdaExpression that it needs to be declared explicitly, here? I don't see this discussed in the following text.


Solution

  • I think I know the answer, but it's weird.

    Here is a quote from chapter 15:

    Precedence among operators is managed by a hierarchy of grammar productions. The lowest precedence operator is the arrow of a lambda expression (->), followed by the assignment operators. Thus, all expressions are syntactically included in the LambdaExpression and AssignmentExpression nonterminals:

    Expression: LambdaExpression AssignmentExpression

    The ConditionalExpression is a part of AssignmentExpression:

    AssignmentExpression: ConditionalExpression Assignment

    As you quote, the third part of ConditionalExpression can be only a ConditionalExpression, not an Expression.

    Making the third part into Expression would include undesirable things like Assignment:

    a? b : c=d // bad idea?
    

    But, limiting the third part to ConditionalExpression rather than Expression leaves out LambdaExpression, so now it needs to be added explicitly with

    ConditionalOrExpression ? Expression : LambdaExpression

    This actually brings the next question: how come Assignmentis OK in the second part of conditional expression but not in the third?