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

Java Predicate implementation can't access global final variable

I created a simple rest service using java, and springboot. here is my service layer code

@Service
class MyService {
    private final TestService service;

    @Autowired
    public MyService(final TestService service) {
        this.service = service;
    }

    // here is the issue
    private final Predicate<User> userPredicate = (user) -> this.service.isValidUser(user);
}

In the above line, the ide complaining about the variable service might not be initialized, and I can not use it in the predicate implementation. I tried removing final to the service, that works, but I do not want to remove final to the TestService declaration.

Anyone have any solution ?

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 :

Execution order is: First all initializing expressions are resolved in lexical order (top to bottom through the file), then the constructor runs.

In other words, that userPredicate = line runs before your this.service = service; line. It’s doomed to failure, and the compiler knows it, so it will refuse to compile this code.

The fix is trivial – move that userPredicate initialization into the constructor:

private final TestService service;
private final Predicate<User> userPredicate;

@AutoWired
public MyService(TestService service) {
  this.service = service;
  this.userPredicate = user -> service.isValidUser(user);
}

For what its worth, if you don’t need the service for anything except making that userPredicate, might as well get rid of the service field entirely.

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