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?