Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a variable from inside lambda

I’ve got a function like the following where I need to update a variable from inside lambda (This is the minimal viable example I could think of without giving our private info so it might not make much sense, but the lambda and stage variables are there).

But as expected, I can’t update the variable since I get the error Variable used in lambda expression should be final or effectively final. What is the best way to update an external variable from within the lambda. The purpose of the variable is to know which stage the process failed in case something goes wrong, which means it can fail without returning anything.

(() -> {

            stage = "Validating";
            //do something
            stage = "Creating x";
            // do something
            stage = "Creating y";
            // .....
            stage = "finalising";
            // do something
        })

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Atomic variables:

AtomicRefence<String> string = new AtomicReference<>();
string.set("Validating");

// some code 

string.get();

more info here -> atomic

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading