-3

This question has to be updated because it is marked as duplicated, but all the linked questions are not completely matching what is tried to be asked:

Is there a reason, that Optional.of(aNullableVar) is required, as Optional.ofNullable(aNullableVar) checks for null pointer inner the method?

As what Savior answered, a purpose may be like a guard clause:

Object object = getObject();
Optional.of(object);
System.out.println(object.toString());

It's equivalent to:

Object object = getObject();
Objects.requireNonNull(object);
System.out.println(object.toString());

and

Object object = getObject();
if (object == null) {
    throw new NullPointerException();
}
System.out.println(object.toString());

Optional.of in Java 8:

public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}

Optional.ofNullable in Java 8:

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}
NVXARM
  • 113
  • 1
  • 5

1 Answers1

3

Optional.of serves a double purpose of constructing an Optional with the given non-null value, but also failing fast if the value is actually null.

It's analogous to doing

Objects.requireNonNull(value);
// and then using value

So nothing would really break, you'd just find out much later that you used a null value to create that Optional when you shouldn't have.

NVXARM
  • 113
  • 1
  • 5
Savior
  • 3,225
  • 4
  • 24
  • 48