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?