I have to call a procedure with the following signature:
private Optional<Address> getAddress()
And I use it to fill a client's record on my system. So, I made the following code to set the address of the record (if it exists).
Optional<Address> address = getAddress();
if (address.isPresent())
record.setAddress(address.get());
However, I get the following notification:
Can be replaced by ifPresent
Reports conditions like if
Optional.isPresent()which could be rewritten in functional style.
So I thought great, I'm going to use this cool ifPresent stuff to simplify my code. Then I came up with this line:
getAddress().ifPresent(x -> record.setAddress(x));
and thought nice, 3 lines into one. But then I got the following message from SonarLint
Replace this lambda with a method reference
and I thought why should I need to create a method just to set a single variable?
Anyway, since I'm kind of new to the use of Optional, I might be misunderstanding something here... So, how should I make this simple piece of code, according to the recommendations and best practices?