How to return when an optional is empty?
You can use ifPresent
and map
methods instead, if the function is void and you need to do side-effects you can use ifPresent
,
optional.ifPresent(System.out::println);
If another method return relies on the Optional than that method might need to return an Optional as well and use the map method
Optional<Integer> getLength(){
Optional<String> hi = Optional.of("hi");
return hi.map(String::length)
}
Most of the time when you call isPresent
and get
, you are misusing Optional
.
You could use orElse(null)
:
String o = getOptional().orElse(null);
if (o == null) {
return;
}