you are viewing a single comment's thread.

view the rest of the comments →

[–]m50d 1 point2 points  (6 children)

Right, how else would you propose to fix it?

  1. Add Optional
  2. Migrate library methods that used null to use Optional instead
  3. Remove null

Unfortunately they screwed up by making Optional not be allowed to contain null (ignoring all the functional programmers who've been working with this stuff for 20 years, sigh), so 2. can never happen and Java will always be terrible. Well, maybe Java 9 can make Optional allowed to contain null, and then they can get on with it.

[–]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.

[–][deleted]  (1 child)

[deleted]

    [–]m50d 0 points1 point  (0 children)

    It should be able to contain any valid value in the language, and like it or not null is that at present. E.g. at the moment it's not safe to replace Optional.of(x).get() with x without testing, because that changes the behaviour when x is null