0

I want to extend Optional to include the reason why the optional is empty, but since Optional is final this cannot be done.

I don't want to use Exceptions because most of my code can just handle the fact that the optional is empty and Exceptions don't mix well with Streams. Only some places care about the additional information.
A solution could be to duplicate the method that calculates the value so that there is one version that returns the Optional and one that throws Exceptions. Duplicated code is harder to maintain though.

My question is more about gaining insight about why the Optional class was made final.

neXus
  • 2,005
  • 3
  • 29
  • 53
  • Lots of classes in the standard libraries are final - one often-cited reason is that immutability guarantees can no longer be upheld if a class is open for extension. – Oliver Charlesworth Mar 24 '17 at 10:44
  • But shouldn't respecting the contract be a responsibility of the one extending it? The actual field containing the value is already private and final, so it cannot be modified by subclasses. Isn't immutability ensured by that? – neXus Mar 24 '17 at 10:51
  • Whose responsibility it is is a subject of debate :) But even if everything's private/final, one could for example override a base-class method with a mutable implementation. – Oliver Charlesworth Mar 24 '17 at 10:54
  • The base-class methods could be made final as well. – neXus Mar 24 '17 at 10:56
  • I just want to use inheritance so that I can use this class transparently as if it was an Optional, but it would provide some other functionality if needed. Inheritance would be the cleanest solution imho, but now I have to resort to either code duplication or composition (which both have impact on already existing code using the optional). – neXus Mar 24 '17 at 11:00
  • 1
    Your intended use case *is* a contradiction, as the identity of `Optional` instances is supposed to be irrelevant, so all empty `Optional` instances should be `equal`, but adding a reason description implies that it becomes relevant, which empty optional instance I have… – Holger Mar 24 '17 at 12:04

0 Answers0