Optional require(s) NonNull
Roland Tepp
luolong at gmail.com
Tue Oct 30 08:02:19 PDT 2012
2012/10/30 Brian Goetz <brian.goetz at oracle.com>
> 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.
>
>
I actually suggested removing get() from Absent (NONE) and only moving it
to instances of Present and only Present.
Pattern matching is not really an issue here, as most of the use cases
where you would use Optional, would need to deal with absent values by any
of the following ways:
1. Use some sensible default value if optional is not present (this is
where I'd use optional.orElse(...) )
2. Throw an exception if optional value is otherwise expected to be present
(i.e. optional.orElseThrow(...))
3. Branch off logic based on the fact if the optional value is present
(checking optional.isPresent())
The danger of having a get() method directly on Optional is that this
encourages the direct use of optional.get() which is susceptible to
NoSuchElementException with the same casualty as NullPointerException's are
common without use of Optional.
Moving it out of the Optional and into the Some/Present will require
explicit casting of the Optional to Present which at least is more
deliberate action and force the developer to consider this at least for a
moment.
i.e. something like this:
Optional<String> optional = ...
if (optional.isPresent()) {
((Present) optional).get().split(...);
}
--
Roland
More information about the lambda-dev
mailing list