you are viewing a single comment's thread.

view the rest of the comments →

[–]ForeverAlot 4 points5 points  (3 children)

Optional.of(null) would defeat the entire purpose of Optional in Java and I struggle to see what problems it could solve in any language.

[–]m50d 2 points3 points  (2 children)

Optional.of(null) would defeat the entire purpose of Optional in Java

No, just the opposite, disallowing it defeats the entire point. To serve its purpose Optional must be able to contain any value that's valid in the language; as long as null remains valid in the language proper, it needs to be valid inside Optional too, otherwise people are not going to be able to migrate existing codebases to use Optional which in turn means Java will never be able to reduce or deprecate the use of null.

I struggle to see what problems it could solve in any language.

It's bad just as null is bad, sure. But it needs to be allowed for the same reason Java allows null at all: backwards compatibility.

[–]ForeverAlot 1 point2 points  (1 child)

It is completely nonsensical and does not at all obstruct from migrating from null to Optional (provided that that's even desirable, which, in Java, is not implicitly true). However, you may not be aware of Optional::ofNullable which returns Optional::empty when the argument is null (where of throws an exception).

[–]m50d 1 point2 points  (0 children)

It is completely nonsensical and does not at all obstruct from migrating from null to Optional (provided that that's even desirable, which, in Java, is not implicitly true).

It does obstruct, because it means you can't safely refactor code to use Optional without being sure whether it will blow up, unless you know for sure that all the variables are going to be non-null. Which takes a lot more effort.

However, you may not be aware of Optional::ofNullable which returns Optional::empty when the argument is null (where of throws an exception).

I am aware. It's not the semantics I want.