- case 1: it can work when using for-each loop:
private void m10(String[] arr) {
for (String s : arr) {
Supplier<String> supplier = () -> {
System.out.println(s);
return null;
};
supplier.get();
}
}
or
private void m10(Object[] arr) {
for (Object s : arr) {
Supplier<String> supplier = () -> {
System.out.println(s);
return null;
};
supplier.get();
}
}
- case 2: it will catch compile-time error
private void m11(String[] arr) {
for (int i = 0; i < arr.length; i++) {
Supplier<String> supplier = () -> {
System.out.println(arr[i]);
return null;
};
supplier.get();
}
}
In case 2, I know the variable i
is not effectively final because its value changed between loop iterations. But I cannot understand why the lambda can work in case 1.