Shouldn't Optional be Serializable?
pete.poulos at gmail.com
Tue Sep 17 18:16:23 PDT 2013
Optional holds data and while the vast majority of use cases for Optional
will be to immediately pull the value out and do something, that doesn't
change the fact that it is still a data structure, somebody somewhere is
going to need to serialize it for some reason. The other data structures
in the java.util package are Serializable so making Optional Serializable
makes things consistent.
As far as I know the cost of adding Serializable to Optional is negligible,
but the cost could be fairly significant to someone who needs to serialize
it at some point and is unable to do so.
Anyhow, I'm currently designing a set of functional (immutable, persistent)
data structures for JDK8+ and I'm debating replacing my "Maybe" class
(functionally the same as Optional, but with Haskell's naming convention
for this data structure) the JDK8 Optional and I'm concerned that the lack
of Serializable on Optional would cause problems for potential users of my
I'm only using Optional/Maybe to wrap return values from methods so I can
indicate missing/present values within my data structures, so I could
conceivably use Optional and still support serialization.
Also, while we are having this discussion, is there an alternative to
serialization that is considered superior? Over the years I have read blog
posts by people condemning serialization, but I don't recall seeing any
On Tue, Sep 17, 2013 at 5:32 PM, Vitaly Davidovich <vitalyd at gmail.com>wrote:
> Presumably because you may want to have class fields that express
> nullability via Optional rather than null. Whether that's a good design or
> not is a separate question; conceptually, I don't see a reason why Optional
> cannot support that. For "reference", Google Guava's version is
> serializable. If someone were to replace their use with jdk's Optional
> then they will hit exceptions if the owner class is serialized.
> Sent from my phone
> On Sep 17, 2013 6:06 PM, "Remi Forax" <forax at univ-mlv.fr> wrote:
> > On 09/17/2013 11:44 PM, Pete Poulos wrote:
> >> Shouldn't java.util.Optional be Serializable? Is there a good reason
> >> it not be?
> > wrong question.
> > the right one is why do you want Optional to be Serializable.
> > Thanks,
> >> Pete
> > cheers,
> > Rémi
More information about the jdk8-dev