Java 8 catch 22 with lambda expressions and effectively final
java, java-8
Solution
The error is coming because your `result` list is not effectively `final` which is a requirement for it's usage in lambda. One option is to declare the variable inside the `if` condition, and `return null;` outside. But I don't think that would be good idea. Your current method is not doing anything productive. It would make much more sense to return an empty list from it.
Having said that all, I would say, since you are playing with Java 8, use `Optional` along with streams here:
public static List<String> catch22(List<String> input) {
return Optional.ofNullable(input)
.orElse(new ArrayList<String>())
.stream().collect(Collectors.toList());
}
And if you want to return `null`, I'll probably change your method to:
public static List<String> catch22(List<String> input) {
if (input == null) return null;
return input.stream().collect(Collectors.toList());
// Or this. B'coz this is really what your code is doing.
return new ArrayList<>(input);
}
Problem
I'm playing with Java 8 and hit a basic scenario that illustrates a catch 22 where fixing one compile error causes another compile error. The scenario (which is just an example simplified from something more complex): ``` public static List<String> catch22(List<String> input) { List<String> result = null; if (input != null) { result = new ArrayList<>(input.size()); input.forEach(e -> result.add(e)); // compile error here } return result; } ``` I get a compile error: Local variable result defined in an enclosing scope must be final or effectively final If I change the first line to: ``` List<String> result; ``` I get a compile error on the last line: The local variable result may not have been initialized It seems like the only approach here is to pre-initialize my result to an ArrayList, which I don't want to do, or not use lambda expressions. Am I missing any other solution?