Here is a piece of code that shows a compilation error that I cannot really explain.
List<?> another = new ArrayList<>();
List<?> nullableList = null;
// this Actually works
Optional<List<?>> a2 = Optional.ofNullable(nullableList);
List<?> result = a2.orElse(another);
// THIS IS NOT ALLOWED!!!! COMPILATION ERROR
Optional.ofNullable(nullableList).orElse(another);
This is the description of Optional.ofNullable
@SuppressWarnings("unchecked")
public static <T> Optional<T> ofNullable(T value) {
return value == null ? (Optional<T>) EMPTY
: new Optional<>(value);
}
In our case, T should be List<?>
so why is it not allowed to do Optional.ofNullable(nullableList).orElse(another);
If anybody can explain why the "two steps" is allowed and why the "one step" is not, that would make my day. Thank you.
> ofNullable(nullableList).orElse(another);`, it will work.
– Holger Feb 07 '22 at 10:01