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?
java.util.Optional
- It's available if you're using JDK 8 or later – whirlwin Oct 5 '16 at 13:44ofNullable()
namedof()
and andof()
namedofNotNull()
– Robert Niestroj Jun 13 '18 at 12:10