Variable is already defined in method lambda

后端 未结 5 904
执念已碎
执念已碎 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条回答
  •  旧时难觅i
    2020-11-30 09:36

    Note, this limitation is going to be removed in the future releases. Quote from JEP-302:

    Lambda parameters are not allowed to shadow variables in the enclosing scopes. (In other words, a lambda behaves like a for statement - see JLS) This often causes problems, as in the following (very common) case:

    Map msi = ...
    ...
    String key = computeSomeKey();
    msi.computeIfAbsent(key, key -> key.length()) //error
    

    Here, the attempt to reuse the name key as a lambda parameter in the computeIfAbsent call fails, as a variable with the same name was already defined in the enclosing context.

    It would be desirable to lift this restriction, and allow lambda parameters (and locals declared with a lambda) to shadow variables defined in enclosing scopes. (One possible argument against is readability: if lambda parameters are allowed to shadow, then in the above example, the identifier 'key' means two different things in the two places where it is used, and there seem to be no syntactic barrier to separate the two usages.)

提交回复
热议问题