Reputation: 1907
I have an instance variable defined as:
final Optional<myClass> myOptional;
I would like to override its toString()
method so that instead of returning "[Optional(the value)]"
it simply returns "(the value)"
(or something else if it's empty). But I can't create a subclass of Optional
since it is apparently final. How can I do this?
Upvotes: 3
Views: 2747
Reputation: 132490
GhostCat is correct in that you cannot subclass Optional
and override its toString
method. However, you can probably get the effect you want by writing this:
String myString = myOptional.map(MyClass::toString).orElse("(empty)")
This sets myString
to the result of the value's toString
method if a value is present, otherwise it substitutes the string (empty)
if the value is absent. Of course, you can put whatever substitute string you want there.
Optional
is final so that it will be easier to convert into a value type in a future version of Java. See Project Valhalla for information about value types, in particular State of the Values for an overview and background.
Optional
is also intended to be immutable, so subclassing must be prevented. See Bloch, Effective Java, Item 15.
Upvotes: 5
Reputation: 140573
You can't.
There is no way of changing the behavior of methods of a class from outside its source code. So, the only choices you got are:
In your case, both options not possible. Sorry, end of story.
(yes, other, interpreted languages would allow you to do so; but Java does not).
Upvotes: 2