Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

java - Java8 Effectively Final compile time error on non final variable

I'm trying to change the boolean variable inside java8 forEach loop to true which is non final. But I'm getting following error : Local variable required defined in an enclosing scope must be final or effectively final.

How to resolve this error?

Code :

boolean required = false; 

This is the variable I have created in the function.

Now when I'm trying to change it :

   map.forEach((key, value) -> {
        System.out.println("Key : " + key + " Value : " + value);
        required = true;
    });

I'm getting the error : Local variable required defined in an enclosing scope must be final or effectively final.

Why this error is arising and how to resolve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot change the local variable from the body of lambda expression. There are several ways to overcome this:

  • In this particular case you can just set boolean required = !map.isEmpty(); without any lambda expression. If you want to set it based on some condition, you can use the Stream API:

    boolean required = map.entrySet().stream().anyMatch(entry -> ...);
    

    This solution is the most preferred.

  • Convert the required variable to the field of the enclosing class.

  • The most dirty way: declare a one-element array: boolean[] required = {false}; and set this element instead: required[0] = true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...