• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

190
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error