Arrow (->) operator precedence/priority is lowest, or priority of assignment/combined assignment is lowest?

后端 未结 2 1863
梦毁少年i
梦毁少年i 2021-02-13 00:27

JLS:

The lowest precedence operator is the arrow of a lambda expression (->), followed by the assignment operators.

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 00:34

    Note the sentence preceding the quoted JLS text:

    Precedence among operators is managed by a hierarchy of grammar productions.

    The grammar of the Java language determines which constructs are possible and implicitly, the operator precedence.

    Even the princeton table you’ve linked states:

    There is no explicit operator precedence table in the Java Language Specification. Different tables on the web and in textbooks disagree in some minor ways.

    So, the grammar of the Java language doesn’t allow lambda expressions to the left of an assignment operator and likewise, doesn’t allow assignments to the left of the ->. So there’s no ambiguity between these operators possible and the precedence rule, though explicitly stated in the JLS, becomes meaningless.

    This allows to compile, e.g. such a gem, without ambiguity:

    static Consumer C;
    static String S;
    public static void main(String[] args)
    {
      Runnable r;
      r = () -> C = s -> S = s;
    }
    

提交回复
热议问题