According to javadoc, Optional.map() returns an Optional.
In the following snippet:
public String getName(Long tpUserId) {
Optional<TpUser> selectedTpUser = tpUserRepo.findById(tpUserId);
return selectedTpUser.map(user -> user.getFirstName() + " " + user.getSurName())
.orElseThrow(() -> new IllegalArgumentException("No user found for this id"));
}
it looks like, I want to return a String but I get an Optional. Nevertheless there is no compile error. Why?
The whole chain of operations returns a String
:
map(...)
) maps the Optional<User>
to an Optional<String>
.orElseThrow(...)
) unwraps the Optional<String>
, thus returning a String
(or throwing an IllegalArgumentException
, if empty).We can find the source code of Optional::map
here.