The final local variable cannot be assigned, since it is defined in an enclosing type in Java

The final local variable cannot be assigned, since it is defined in an enclosing type in Java

While I was working on the following piece of code

 try {
            JPA.withTransaction(dbName, false,
                    new play.libs.F.Function0() {
                        @Override
                        public Void apply() throws Throwable {
                            // System.out.println(play.db.jpa.JPA.em(dbName).contains(BHA.class));
                            List proActBHAList = BHA.findByWellUid(dbName, wellUid);
                            bhaList = proActBHAList;
                            return null;
                        }
                    });
        } catch (Throwable throwable) {
            Logger.error("Error: ", throwable);
        }

Initially the bhaList was a local variable. It was giving a compilation error Cannot refer to the non-final local variable bhaList defined in an enclosing scope.

The point is that method-local variables from the enclosing type are actually copied to instances of anonymous classes which is why they need to be final, because the variable in the nested type instance is not the same anymore.

I converted the local variable bhaList  to an instance variable to resolve the issue.

A good read that helped me to solve from problem

http://stackoverflow.com/questions/10166521/the-final-local-variable-cannot-be-assigned

http://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class


No comments:

 My Attempt to learn AI  GPT Generative Pretrained Transformer Created by Google in 2017 with the publication of the paper "Attention ...

Popular in last 30 days