SerializableOptional

nicolaiparlog edited this page Nov 22, 2014 · 2 revisions

This feature mitigates the problems caused by the fact that Java 8's Optional is not serializable.

After describing the concept some examples are given. More can be found in the self-contained demo. The comment on SerializableOptional gives a detailed explanation of how it can be used.

Concept

This feature only consists of the class SerializableOptional, which simply wraps an Optional but is serializable.

There are several ways to use this class:

  • as a return or argument type for methods which need all instances going in and coming out to be serializable
  • as a field type in a serializable class
  • as a replacement for Optional when writing to the output stream

Examples

Switching between Optional and SerializableOptional is easy:

Optional<String> someOptional;
SerializableOptional<String> serializableOptional =
		SerializableOptional.fromOptional(someOptional);
Optional<String> optional = serializableOptional.asOptional();

It is not necessary to first create an Optional. SerializableOptional provides equivalents of Optionals static factory methods:

SerializableOptional<String> empty = SerializableOptional.empty();
SerializableOptional<String> full = SerializableOptional.of("value");
SerializableOptional<String> maybe = SerializableOptional.ofNullable(string);

Calls to methods using this class as an argument or return type look like this:

// 'search' return a 'SerializableOptional'; unwrap it using 'asOptional'
Optional<String> searchResult = search(id).asOptional();
// 'log's second argument is of type 'SerializableOptional';
// wrap the optional using 'fromOptional'
log(id, SerializableOptional.fromOptional(searchResult));