Reputation: 1986
I am trying to fetch some data from and object. I have a small piece of code where:
UserAccessValidator
is just a validator, the method validateAccessToAccount
takes an Long
, and throws and exception when the access is not granted. Simple as that.
userAccessValidator.validateAccessToAccount(
peripheralRepository.findById(peripheralId)
.ifPresentOrElse(p -> p.getAccount().getId(),
() -> {throw new NotFoundException(Peripheral.class);}));
It doesn't compile, i get an information that Long
is required but provided is void.
How can I fix this piece of code for it to work? I would like to get the account Id, but I do not know how to achieve this... A more detailed explaination would be very appreciated ;)
Upvotes: 1
Views: 108
Reputation: 393836
ifPresentOrElse()
has a void return type, so it's not suitable to return a value.
Use map
to map the value inside the Optional
into the desired account ID. This would return another Optional
.
Then you can call orElseThrow
, which would throw the exception if the Optional
is empty, and return the value stored within that Optional
if not.
userAccessValidator.validateAccessToAccount(
peripheralRepository.findById(peripheralId)
.map(p -> p.getAccount().getId())
.orElseThrow (() -> {throw new NotFoundException(Peripheral.class);});
Upvotes: 1