java.util.Optional fields

Vitaly Davidovich vitalyd at gmail.com
Fri Sep 21 05:19:34 PDT 2012


Why not implement this like Guava with two concrete subtypes of Optional:
Present and Absent? It seems cleaner and I don't think performance will be
worse as compiler will only ever see two possible receivers and can use a
PIC to eliminate calls via vtable in those cases.

Sent from my phone
On Sep 21, 2012 7:42 AM, "Peter Levart" <peter.levart at gmail.com> wrote:

> Maybe the intention was to allow null values to be wrapped in non-empty
> Optional? In that case the check for non-null in constructor is wrong...
>
> Regards, Peter
>
> On 09/21/2012 01:35 PM, Peter Levart wrote:
> > Hi all,
> >
> > I'm just thinking about the implementation of current java.util.Optional.
> >
> > It has 2 fields: "T value" and "boolean present".
> >
> > But since the invariant is:
> >
> >     public Optional(T value) {
> >         this.value = Objects.requireNonNull(value);
> >         this.present = true;
> >     }
> >
> >     private Optional() {
> >         this.value = null;
> >         this.present = false;
> >     }
> >
> > // value != null && present || value == null && !present.
> >
> > Isn't the "present" flag superfluous? Or is this intentional? Is the
> > test for boolean faster that the check for reference equality with
> > null? Does additional boolean flag, considering alignment constraints,
> > produce a larger object or does it not?
> >
> > Regards, Peter
> >
>
>
>


More information about the lambda-dev mailing list