I know we have Optional.ofNullable()
if the value can also be null. My question is, why isn't that the default behaviour for Optional.of()
as well? If a value can not be null
, why put in in the Optional
in the first place? If it turns out to be null anyway, you will get an NPE all the same anyway. If you construct an Optional
with the of()
method, you will still have all the other methods of the Optional
wrapper which only really have a purpose if the value can be null
.
Edit: I have read Why use Optional.of over Optional.ofNullable? before posting this, but the answer there was "because you catch the error sooner, and it's easier to trace it that way". But I kinda disagree with that, maybe you will have a few extra lines in your stacktrace, but it's still easy to pinpoint the source of the NPE.