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


    @Test

    public void counterTest() {

    int count = 0;

   

    IntStream.range(0, 10)

    .forEach(i -> {

    count++; // Local variable count defined in an enclosing scope must be final or effectively final

    });

   

    System.out.println(count);

    }



[증상]


익명함수에서 로컬변수를 수정할 수 없는 현상.




[해결방법]


1. 로컬변수를 클래스 멤버로 변경한다.


    int count;

    

    @Test

    public void counterTest() {

    count = 0;

   

    IntStream.range(0, 10)

    .forEach(i -> {

    count++; // OK

    });

   

    System.out.println(count);

    }



2. AtomicInteger 를 사용한다.


    @Test

    public void counterTest() {

    AtomicInteger count = new AtomicInteger(0);

   

    IntStream.range(0, 10)

    .forEach(i -> {

    count.incrementAndGet();

    });

   

    System.out.println(count.get());

    }


3. array를 사용하는것도 같은 방법.


    @Test

    public void counterTest() {

    final int[] count = { 0, };

   

    IntStream.range(0, 10)

    .forEach(i -> {

    count[0]++;

    });

   

    System.out.println(count[0]);

    }


https://stackoverflow.com/a/30213098



4. Consumer... 

+ Recent posts