Java 8's Optional is not serializable, and this was a deliberate design decision. Three main reasons are explored: (1) Optional was designed purely as a return type with a very short lifespan, making serialization unnecessary; (2) making JDK classes serializable freezes their internal representation forever, creating significant maintenance burden; (3) Optional is a value-based class, and value-based classes must avoid identity-sensitive mechanisms like serialization to allow future compiler optimizations toward value types. The post also notes some inconsistencies in this reasoning, such as other value-based classes like LocalDate being serializable, and that equals/hashCode were added despite similar concerns about misuse.

8m read timeFrom nipafx.dev
Post cover image
Table of contents
▚ Shouldn't Optional Be Serializable?▚ Return Type▚ Lock-In by Serialization▚ Value Types▚ Reflection

Sort: