• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

26
Views
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 ?

4 months ago ·

Santiago Trujillo

1 answers
Answer question

0

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.

4 months ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.