Variable is already defined in method lambda

后端 未结 5 897
执念已碎
执念已碎 2020-11-30 08:59

Consider the following almost compilable Java 8 code:

public static void main(String[] args) {

    LinkedList users = null;
    users.a         


        
5条回答
  •  失恋的感觉
    2020-11-30 09:35

    The question is pretty old, but i thought my answer can add better clarity to the already given answers. Particularly to that of @Sotirios Delimanolis . The lambda assignment in

        User user = users.stream().filter((user) -> user.getId() == 1).findAny().get();
    

    fails for the same reason the following code fails.

        Object e = null;
        try{
          throw new Exception();
        } catch(Exception e) { // compilation fails because of duplicate declaration
          //do nothing
        }
    

    A local variable (§14.4), formal parameter (§8.4.1, §15.27.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name, not a qualified name (§6.2).

    Some declarations are not permitted within the scope of a local variable, formal parameter, exception parameter, or local class declaration because it would be impossible to distinguish between the declared entities using only simple names.

    Because lambdas have the same scope of all the things mentioned above, this fails.

提交回复
热议问题