Apollo
Apollo

Reputation: 1822

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

Upvotes: 1

Views: 805

Answers (1)

DEV
DEV

Reputation: 1736

How about using ifPresent :

customer.getFirstName().ifPresent(name1->
  customer.getLastName().ifPresent(name2->
      final String firstName = name1;
      final String lastName = name2;
  );
);

Upvotes: 2

Related Questions