Optional require(s) NonNull
Roland Tepp
luolong at gmail.com
Tue Oct 30 06:48:58 PDT 2012
No, it doesn't.
That's why there are orElse* methods.
In most of the cases I've used homebrewed Optional pattern, these are more
than enough.
The whole point is to make the code safer from NPE's by throwing the
"optionality" of the value in your face and forcing you to deal with it
explicitly.
So instead of writing code like this:
String someString = ...
if (someString == null) {
someString = "some default string";
}
someString.split(...);
you would write:
Optional<String> optionalString = ...
optionalString.orElse("some default string").split(...);
Much cleaner and easier to understand imho and completely safe from
accidental NPE.
Current design will simply replace NPE with NSEE (NoSuchElementException)
in case a "wrong kind of Optional" is provided.
On the other hand, the separate type implementation is intentional. User of
the Optional has to explicitly deal with the fact that the value might not
be present and check for isPresent() if they need to call get() directly on
Optional. The risk of running into ClassCastException is explicit and
deliberate.
2012/10/30 Alessio Stalla <alessiostalla at gmail.com>
> In Java there isn't any pattern matching construct, so such a design
> would force users to write ugly code with instanceof's and type casts.
>
--
Roland
More information about the lambda-dev
mailing list