Java 8 Lambda Variable Scope

I have 2 code examples:

int[] idx = { 0 };
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
list.add("ghi");
list.stream().forEach(item -> {
    System.out.println(idx[0] + ": " + item);
    idx[0]++;
});

We work correctly.

Although this code has a compilation error:

int idx = 0;
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
list.add("ghi");
list.stream().forEach(item -> {
    System.out.println(idx + ": " + item);
    idx++;
});

Saying:

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

The only difference is the idxint or int array.

What is the reason?

+4
source share
3 answers

The main reason is that the JVM does not have mechanisms for constructing references to local variables, which is necessary for execution idx++when it idxis inteither some immutable type (for example, String). Since you are trying to mutate idx, just grabbing its value will not be enough; Java will need to grab the link and then change the value through it.

Java , . Java , , . , Java .

make idx static , . ?

, . , .

, , idx - . idx this, .

+6

. Java 8 , . int[] idx = { 0 }; . , int idx , . - , , .. final int idx = 0.

+2

, , .

1:

int[] idx , idx[0]++; idx = {1};,

2: ​​

idx++;

+1

Source: https://habr.com/ru/post/1662250/


All Articles