3 ms·
As the sibling comment says, the post's advice is really about making your code refactoring-friendly with regard to type checking. You generally would not want
by oftenwrong 7y ago
As the sibling comment says, the post's advice is really about making your code refactoring-friendly with regard to type checking.
You generally would not want to call '.get()' without an 'isPresent()' check because it will throw a NoSuchElementException if the Optional is empty. This is a foreseeable case, so most would like to handle it somewhat explicitly.
Today, it is idiomatic to use '.map' to transform it:
Optional<String> foo = optionalCountry.map(Country::getName);
You can also throw a domain-specific exception from that point:
Optional<String> foo = optionalCountry
.map(Country::getName)
.orElseThrow(...);
- chopin 7y agoorElseThrow does return a String, not an Optional. You also could use orElse(null) or orElse("null") depending on the use case (eg. using as a part of toString).
- oftenwrong 7y agoI'm useless without a compiler to check my types!