I understand the concept of final / effectively final within lambda , it essentially protects from side effects. However why the following code snippet works? Is it also not violating this behaviour?
import java.util.stream.Stream;
public class Learn {
int x = 0;
Stream<Integer> numbers() {
x = x +1;
return Stream.iterate(0, i -> {
int result = x + i;
x = i;
return result;
});
}
public static void main(String[] args) {
Learn l = new Learn();
l.numbers()
.skip(20) // Don't use the first 20
.limit(10) // Then take 10 of them
.forEach(System.out::println);
System.out.println("=====================");
System.out.println(l.x);
}
}
75025
121393
196418
317811
514229
=====================
317811