In Java, I have the following code
List<Integer> myList = new ArrayList<>(); for (int i=0;i<9;i++) { myList.add(i); } Integer sum = 0; myList.forEach(i -> { sum = sum + i; // does not compile, sum needs to be final or effectively final }); for(int i : myList) { sum = sum + i; //runs without problems }
My question is: why can't I change the value of the sum from lambda? Does it do the same as for the cycle below, or am I wrong? It is also interesting that if I declare an Integer sum outside the main method as static, it also works. Can someone explain to me why?
EDIT: in another similar question, Does Java 8 support closure , the answer is as follows:
it is a combination of backward compatibility and project resource limits.
However, I still can not understand why it works if I make the sum an array or declare it outside the main one. I would also like to understand the difference between myList.forEach and the for loop below, why one works and the other doesn't.
source share