我正在玩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;
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误:
在封闭范围内定义的局部变量结果必须是最终的或有效的最终结果
如果我将第一行更改为:
List<String> result;
Run Code Online (Sandbox Code Playgroud)
我在最后一行收到编译错误:
局部变量结果可能尚未初始化
似乎这里唯一的方法是将我的结果预初始化为ArrayList,我不想这样做,或者不使用lambda表达式.我错过了任何其他解决方案吗?
Roh*_*ain 17
错误即将发生,因为您的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());
}
Run Code Online (Sandbox Code Playgroud)
如果你想返回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);
}
Run Code Online (Sandbox Code Playgroud)
Rau*_*uiu 10
使用input!= null在块内推送声明.例:
public static List<String> catch22(List<String> input) {
if (input != null) {
List<String> result;
result = new ArrayList<>(input.size());
input.forEach(e -> result.add(e)); // compile error here
return result;
} else {
return null; // or empty list or something that suits your app
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27030 次 |
| 最近记录: |