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

"Optional value should only be accessed after calling isPresent()" although checked in if for multiple values

I receive a Customer object which contains lastName and firstName. In the conversion I check if both values are not empty and then pass them into the DTO:

if (customer.getFirstName().isPresent() && customer.getLastName().isPresent()) {
      final String firstName = customer.getFirstName().get();
      final String lastName = customer.getLastName().get();
      // do assignment
}

But I still get the Sonar message Optional value should only be accessed after calling isPresent().

Am I missing something here or is this a false positive?

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 :

How about using ifPresent :

customer.getFirstName().ifPresent(name1->
  customer.getLastName().ifPresent(name2->
      final String firstName = name1;
      final String lastName = name2;
  );
);
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