gpt4 book ai didi

Java 8 catch 22 与 lambda 表达式和有效的 final

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:02 25 4
gpt4 key购买 nike

我正在玩 Java 8 并遇到了一个基本场景,该场景说明了陷阱 22,其中修复一个编译错误会导致另一个编译错误。场景(这只是一个从更复杂的东西简化而来的例子):

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

编译错误:

Local variable result defined in an enclosing scope must be final or effectively final

如果我将第一行更改为:

List<String> result;

最后一行出现编译错误:

The local variable result may not have been initialized

似乎这里唯一的方法是将我的结果预初始化为 ArrayList,我不想这样做,或者不使用 lambda 表达式。我是否缺少任何其他解决方案?

最佳答案

出现错误是因为您的result 列表不是有效的final,这是在lambda 中使用它的要求。一种选择是在 if 条件内声明变量,并在外部 return null; 。但我认为这不是个好主意。您当前的方法没有做任何有成效的事情。从中返回一个空列表会更有意义。

说了这么多,我想说的是,既然你在玩 Java 8,请使用 Optional连同此处的流:

public static List<String> catch22(List<String> input) {
return Optional.ofNullable(input)
.orElse(new ArrayList<String>())
.stream().collect(Collectors.toList());
}

如果您想返回null,我可能会将您的方法更改为:

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

关于Java 8 catch 22 与 lambda 表达式和有效的 final,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22777915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com