Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional cannot be applied to interface

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?

like image 309
Nikolas Charalambidis Avatar asked Jan 17 '19 14:01

Nikolas Charalambidis


1 Answers

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.

like image 106
Nikolas Charalambidis Avatar answered Sep 20 '22 09:09

Nikolas Charalambidis