Java 8 Optional cannot be applied to interface

Nikolas :

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?

Nikolas :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36610&siteId=1
Recommended