0

At line names.forEach(s -> count++); of the below program, the compiler is giving error - "Local variable count defined in an enclosing scope must be final or effectively final".

How can this error be resolved?

Note: The requirement is not to find the size of the list. It's just an example of the error. I, actually, want to understand the issue and know how it can be addressed in the below program.

public static void main(String[] args) {
    List<String> names = new ArrayList<>();
    names.add("Tom");
    names.add("Dick");
    names.add("Harry");

    int count=0;
    names.forEach(s -> count++); //ERROR IN THIS LINE
    System.out.println("Size of List = "+count);
}
JavaYouth
  • 1,536
  • 7
  • 21
  • 39
  • declare count final. sure, you'll have trouble adding anything, so you could use a composite object in which you keep the counter. but for something that can be replaced with: sop(names.size()); why bother? – Stultuske May 27 '19 at 05:49
  • Well, `List` does have a `size()` method... – MC Emperor May 27 '19 at 05:50
  • I want to understand and overcome this error. My requirement is not to get the size of the list but to know how to get through this problem. So I have just given this example. Thanks – JavaYouth May 27 '19 at 05:52
  • As a general rule, lambdas should avoid leaking scope. You could pass the lambda value to another method or thread, and cause what was once thread-safe code to become prone to race-conditions or other concurrency related problems. If you really want to hack around this problem you could get away with a final container and mutate the value inside. i.e. `final int[1] ...` That said, there are much better options such as the `sum` stream operator or `reduce` method which allow you to solve this problem in a thread-safe functional manner. – flakes May 27 '19 at 05:58
  • @TimBiegeleisen I kinda disagree with the close duplicate on that answer. It gives a definition relevant to the question at hand, but does not actually solve their problem. – flakes May 27 '19 at 06:00
  • 1
    @flakes but what is the problem? The OP said, it’s not about getting the list’s size, which could be done via `size()` (or `stream().count()` if you want a `long`). So this question is about an inappropriate solution to an unspecified problem. So whether the linked question solves the problem, is irrelevant, in its current form, we can’t solve the problem anyway. – Holger May 27 '19 at 07:58
  • @Holger Fair enough, it's just that this *might* be misleading as a close-dup. There are other more relevant choices to close by. – flakes May 27 '19 at 08:29
  • @flakes feel free to suggest better questions; I can add them. – Holger May 27 '19 at 08:32

0 Answers0