Q: if an optional is empty, will it remain forever empty?
— An Optional.java variable could but should never be null, as this instance need a state to hold at least the boolean isPresent.
If a method is declared to return Optional<C>, then the author need to ensure she doesn’t return a null Optional ! This is not guaranteed by the language.
https://dzone.com/articles/considerations-when-returning-java-8s-optional-from-a-method illustrates a simple rule — use a local var retVal throughout then, at the very last moment, return Optional.ofNullable(retVal). This way, retVal can be null but the returned reference is never null.
If needed, an Optional variable should be initialized to Optional.empty() rather than null.
https://dzone.com/articles/considerations-when-returning-java-8s-optional-from-a-method shows the pitfalls of returning Optional from a method.
I feel this is like borrowing from a loan shark to avoid accidental credit card interest charge.
If you are careful, it can help you avoid the NPE of the traditional practice, but if you are undisciplined (like most of us), then this new stragey is even worse —
Traditional return type is something like String, but caller has to deal with nulls. New strategy is supposed to remove the risk/doubt of a null return value, but alas, caller still needs to check null first, before checking against empty!
–immutability is tricky
- the referent object is mutable
- the Optional reference can be reseated, i.e. not q[ final ]
- the Optional instance itself is immutable.
- Therefore, I think an Optional == a mutable ptr to a const wrapper object enclosing a regular ptr to a mutable java object.
Similarity to String.java — [B/C]
Compare to shared_ptr instance — [A] is true.
- C) In contrast, a shared_ptr instance has mutable State, in terms of refcount etc
- B) I say Not-applicable as I seldom use a pointer to a shared_ptr
— get() can throw exception if not present
— not serializable
— My motivation for learning Optional is 1) QQ 2) simplify my design in a common yet simple scenario
https://www.mkyong.com/java8/java-8-optional-in-depth/ is a demo, featuring … flatMap() !!