Using Optional, I want to return a certain implementation (First or Second) of an interface according to the mapping result. This is the interface that First and Second implement:
public interface MyInterface {
    Number number();
}
The following Optional usage is erroneous:
final String string = ...                          // might be null
final Number number = Optional.ofNullable(string)
        .map(string -> new First())
        .orElse(new Second())                      // erroneous line
        .number();
orElse
(com.mycompany.First)in Optional cannot be applied to(com.mycompany.Second)
Why is the line erroneous since both of the classes First and Second implement the interface MyInterface and the method MyInterface::number returns Number? How to implement this correctly?
I have discovered out that the method Optional::map returns U which doesn't allow apply returned First to another type such Second is. An explicit casting to its interface or requiring it within the map method is a way to go:
final Number number = Optional.ofNullable("")
        .<MyInterface>map(string -> new First())
        .orElse(new Second())
        .number(); 
__
Edit: I have found this out after posting the question. However, I am keeping both since I haven't found a similar solution anywhere else yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With