I'm having a strange behaviour with Generics I'm using Java8.
Here is a small sample code to demonstrate the problem Following code works fine without any issues with type inference. where, SpecificError is a subtype of GenericError.
public GenericType<AbstractError> method{
Optional<SpecificError> error = Optional.of(new SpecificError());
if (error.isPresent()) {
return GenericType.error(error.get());
} else {
// return something else
}
}
I have lot of this places in the code, where I had to do this if/else checks with optional, I decided to make a new function which receives the Optional, checks for presence and returns the Generic type object New function code:
public static <R extends AbstractError> GenericType<R> shortcut(Optional<R> error) {
if (error.isPresent()) {
return GenericType.error(error.get());
} else {
// something else
}
}
This is new code calling the above function:
public GenericType<AbstractError> method{
Optional<SpecificError> error = Optional.of(new SpecificError());
return GenericType.shortcut(error);
}
And strangely this does not work and breaks the following compilation error:
[ERROR] inferred: AbstractError
[ERROR] equality constraints(s): AbstractError, SpecificError
I just do not understand, why this won't work. The only thing, I have done is to make a small function which the job of doing isPresent check on Optional, everything else is the same. Why can't Java see that SpecificError is subtype of AbstractError