Java lambdas have different variable requirements than anonymous inner classes

后端 未结 3 1443
北海茫月
北海茫月 2021-01-03 21:33

I have an anonymous inner class and an equivalent lambda. Why are the variable initialization rules stricter for the lambda, and is there a solution cleaner than an anonymou

3条回答
  •  时光说笑
    2021-01-03 21:49

    In my case, I had a Predicate which was trying to access a private final instance variable. I made the Predicate final as well which fixed it.

    Before - Compiler error, this.availableCities might not have been initialized

    class Service {
      private final List availableCities;
      Service(List availableCities) {
        this.availableCities = availableCities;
      }
      private Predicate isCityAvailable = city -> this.availableCities.contains(city);
    }
    

    After - No more error

    class Service {
      private final List availableCities;
      private final Predicate isCityAvailable;
      Service(List availableCities) {
        this.availableCities = availableCities;
        this.isCityAvailable = city -> this.availableCities.contains(city);
      }
    }
    

    I think the "may not have been initialized" compiler error has some merit, since otherwise there's nothing stopping you from calling the Predicate from within the constructor before the final instance variable is initialized:

    Potentially Why the Compiler Enforces This

    class Service {
      private final List availableCities;
      Service(List availableCities, String topCity) {
        boolean isTopCityAvailable = isCityAvailable.test(topCity); // Error: this.availableCities is not initialized yet
        this.availableCities = availableCities;
      }
      private Predicate isCityAvailable = city -> this.availableCities.contains(city);
    }
    

提交回复
热议问题