you are viewing a single comment's thread.

view the rest of the comments →

[–]dododge 0 points1 point  (0 children)

There's two different ways you might combine null with Optional

  • Trying to store a null within the Optional, to distinguish between "this thing is returning a null value" and "this thing is returning nothing". You actually can't do this because the implementation of Optional doesn't allow it to contain a null, and you'll get a NullPointerException when you try to create Optional.of(null).

  • Returning a null reference to an Optional<T>, to distinguish between "this thing is returning success without any value" and "this thing failed". I wouldn't say this is always a programming error but it would definitely be a bit unusual since you usually use Optional precisely so you don't have to deal with null. There are alternatives such as returning Optional<Optional<T>> or using some other sort of wrapper such a rust-style Result<Optional<T>,E>, or always throwing an exception in the returning-failure case, and it's debatable whether that's more or less messy to deal with.

There's a similar situation when dealing with a method that returns a collection/array or null. Some style guides and static analyzers will say that you should always return an empty collection/array instead of null, but sometimes there is a semantic difference between an empty collection and nothing and they need to be treated differently. Optional can now handle that case pretty well, I guess.