Java lambda - for loop counter is not effectively final

后端 未结 4 1892
感情败类
感情败类 2021-01-19 00:18

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final

4条回答
  •  迷失自我
    2021-01-19 00:47

    From the Java Language Specification

    The scope of a local variable declared in the ForInit part of a basic for statement (§14.14.1) includes all of the following:

    • Its own initializer
    • Any further declarators to the right in the ForInit part of the for statement
    • The Expression and ForUpdate parts of the for statement
    • The contained Statement

    And about effectively final

    A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not declared final but it never occurs as the left hand operand of an assignment operator (§15.26) or as the operand of a prefix or postfix increment or decrement operator

    Your i variable occurs as the operand of postfix increment operator

    i++
    

    It is therefore not effectively final and can not be captured by the lambda.

提交回复
热议问题