Optional require(s) NonNull

Roland Tepp luolong at gmail.com
Tue Oct 30 06:16:42 PDT 2012


Hi,

I was wondering, what is the rationale in implementing the Optional this
particular way?
(there is a thread on Java posse google group where various deficiencies of
current implementation are discussed at some length:
https://groups.google.com/forum/#!topic/javaposse/fTDnkfeSHsY)

I myself would like to ask why have you not implemented it same way as most
implementations of Optional I've seen have done it, by having two separate
classes for Absent and Present values
(I attached my take on the Optional implementation to this email).

This addresses imho very nicely the usual conceptual difference between
values that are present and those that are not.
Only present values have get method, so there is no way to accidentally get
from an absent value.
The implementation of individual getters in concrete subclasses is
extremely straight forward, so potentially it is also more performant
(granted, I know next to nothing of the compilers and low level JVM
optimizations).

There is also a if Optional should implement Stream API, as that would make
it so much more useful in general...

2012/10/29 Brian Goetz <brian.goetz at oracle.com>

> Take a look at the code today :)
>
> On Oct 29, 2012, at 12:33 PM, Boaz Nahum wrote:
>
> > I can only blame my poor English.
> >
> > Lets forget the 'philosophic' first  part of my question.
> >
> > the  second part  asks: According to current implementation in b62,
> > 'this.present' is false i.f.f   'this.value' is null --> 'this.present'
> ==
> > (this.value != null ). So why we need 'this.present' ?
> >
> > If you allow me insist of the first part - Why won't allow me to create
>  a
> > *present* Optional with null value ?
> >
> > On Mon, Oct 29, 2012 at 5:15 PM, Brian Goetz <brian.goetz at oracle.com>
> wrote:
> >
> >> This constructor is for creating a *present* Optional.  You use
> >> Optional.empty() to create an *empty* optional.
> >>
> >> On Oct 29, 2012, at 11:02 AM, Boaz Nahum wrote:
> >>
> >>> I thought I understand Optional till I read the implementation:
> >>>
> >>> public Optional(T value) {
> >>>       this.value = Objects.requireNonNull(value);
> >>>       this.present = true;
> >>> }
> >>>
> >>> Why 'requireNonNull' non null ? If null is singular value why we need
> >> this
> >>> class ? just for 'orElse..' methods ?
> >>>
> >>> If if value can't be null why we need the 'present' field ?
> >>>
> >>> My hopes where that I can use Optional to return a null as a legal
> value.
> >>>
> >>> Thanks
> >>> Boaz
> >>>
> >>
> >>
> >
>
>
>


-- 
Roland


More information about the lambda-dev mailing list