When using the Java 8 Optional
class, there are two ways in which a value can be wrapped in an optional.
String foobar = <value or null>;
Optional.of(foobar); // May throw NullPointerException
Optional.ofNullable(foobar); // Safe from NullPointerException
I understand Optional.ofNullable
is the only safe way of using Optional
, but why does Optional.of
exist at all? Why not just use Optional.ofNullable
and be on the safe side at all times?
This question is related to
java
java-8
nullpointerexception
null
optional
Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.
This depends upon scenarios.
Let's say you have some business functionality and you need to process something with that value further but having null
value at time of processing would impact it.
Then, in that case, you can use Optional<?>
.
String nullName = null;
String name = Optional.ofNullable(nullName)
.map(<doSomething>)
.orElse("Default value in case of null");
In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(NullPointerException::new);
// .orElseThrow(CustomException::new);
Source: Stackoverflow.com