I want to declare the return type of a method as the intersection of a type variable and a static interface (say java.io.Serializable
).
Ideally, I want to be able to do the following:
public class Main {
public static <I, T extends I & java.io.Serializable> T foo(I object) {
return null;
}
}
However, this code gives the following compilation error:
Main.java:3: error: a type variable may not be followed by other bounds
public static <I, T extends I & java.io.Serializable> T foo(I object) {
^
1 error
According to the documentations of Java type intersection, this should be possible.
The form of a bound is restricted (only the first element may be a class or type variable, and only one type variable may appear in the bound) to preclude certain awkward situations coming into existence.
The error seems clear, but yet no mention to such a restriction in the documentations. As far as I understand, if type variables cannot occur after the first place since an interface is required, and cannot be followed by any other bound as the error says, that would mean that type variables cannot be used in type intersection as such.
Oracle documentations seem to state the otherwise.
Thanks for the insights.