问题
I am thinking about constrained type inference at the call site of a function. In the following snippet I get a compile error for the first inference call in the main function as expected (String
is not a subtype of X
so we should not be able to infer this type) but I do not get a compile error when I replace the abstract class with an interface and do the same thing even though clearly String
is not a subtype of Y
. This must be a compiler bug right? (I have tried with jdk 1.8.121 + 1.8.161).
public class Why
{
static abstract class X
{
}
static <Z extends X> Z infer1()
{
return null;
}
static interface Y
{
}
static <Z extends Y> Z infer2()
{
return null;
}
public static void main(String[] args)
{
String x = infer1();
String y = infer2();
}
}
来源:https://stackoverflow.com/questions/56044697/is-this-a-java-generic-type-inference-compiler-bug