Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
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 ?

over 4 years 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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!