Optional require(s) NonNull
Brian Goetz
brian.goetz at oracle.com
Tue Oct 30 07:18:06 PDT 2012
Then what's the problem? We have these methods already.
You suggested moving get to Some/None, and Alessio told you exactly why that was a silly idea.
On Oct 30, 2012, at 9:48 AM, Roland Tepp wrote:
> 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