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
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);
}