Java 8 Optional cannot be applied to interface
I would write that without an explicit cast:
Optional.ofNullable(string)
.map(s -> {
MyInterface m = new First();
return m;
})
.orElse(new Second())
.number();
The problem is that Java infers the mapped type to be First
, and Second
is not an instance of First
. You need to explicitly give Java a bit of a nudge to know the right type:
private static void main(String... args)
{
final String string = "";
final Number number = Optional.ofNullable(string)
.<MyInterface>map(str -> new First()) // Explicit type specified
.orElse(new Second())
.number();
}
This is a generic limitation of type inference along method chains. It's not limited to Optional
.
There has been some suggestion to have type inference work along method chains. See this question: Generic type inference not working with method chaining?
Maybe in a future version of Java the compiler will be clever enough to figure this out. Who knows.
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.