I have a problem understanding captures in type inference. I have some code that looks like this:
import java.util.EnumSet;
class A {
static enum E1 {
X
}
private static <T extends Enum<T>> EnumSet<T> barEnum(Class<T> x) {
return null;
}
private static void foo1(EnumSet<E1> s, E1 e) {
EnumSet<E1> x2 = barEnum(e.getClass());
}
private static void foo2(EnumSet<E1> s) {
EnumSet<E1> x = barEnum(s.iterator().next().getClass());
}
}
This gives two errors when compiling:
Test.java:15: error: method barEnum in class A cannot be applied to given types;
EnumSet<E1> x2 = barEnum(e.getClass());
^
required: Class<T>
found: Class<CAP#1>
reason: inference variable T has incompatible equality constraints E1,CAP#2
where T is a type-variable:
T extends Enum<T> declared in method <T>barEnum(Class<T>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends E1 from capture of ? extends E1
CAP#2 extends E1 from capture of ? extends E1
Test.java:19: error: method barEnum in class A cannot be applied to given types;
EnumSet<E1> x = barEnum(s.iterator().next().getClass());
^
required: Class<T>
found: Class<CAP#1>
reason: inference variable T has incompatible equality constraints E1,CAP#2
where T is a type-variable:
T extends Enum<T> declared in method <T>barEnum(Class<T>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends E1 from capture of ? extends E1
CAP#2 extends E1 from capture of ? extends E1
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
While trying to understand the error, I changed foo2
to capture the value of getClass()
in a local variable to see the actual type:
private static void foo2(EnumSet<E1> s) {
// this works
Class<? extends Enum> c = s.iterator().next().getClass();
EnumSet<E1> y = barEnum(c);
}
Now, the error disappeared and the code is compiled. I don't understand how the introduction of a local variable with the exact same type as the expression changes the type inference algorithm and solves the problem.