8
Suppose we have a class like this:
public class xx {
public interface Foo<T> {
T getValue();
void setValue(T value);
}
public void resetFoos(Iterable<Foo<?>> foos) {
for (Foo<?> foo : foos)
foo.setValue(foo.getValue());
}
}
It will fail to compile even though intuitively it seems like it "should":
xx.java:10: setValue(capture#496 of ?) in xx.Foo<capture#496 of ?> cannot be applied to (java.lang.Object)
foo.setValue(foo.getValue());
The reason is that foo does not have a bound generic type, so the compiler doesn't "know" that the output of foo.getValue() is compatible with the input of foo.setValue().
So to fix this you have to create a new method just for the purpose of binding the generic type parameter in the for() loop:
public class xx {
public interface Foo<T> {
T getValue();
void setValue(T value);
}
public void resetFoos(Iterable<Foo<?>> foos) {
for (Foo<?> foo : foos)
this.resetFoo(foo);
}
// stupid extra method here just to bind <T>
private <T> void resetFoo(Foo<T> foo) {
foo.setValue(foo.getValue());
}
}
This has always annoyed me. Plus, it seems like there can be a simple solution.
My question: Is there any "good" reason why the java language shouldn't be extended to allow generic type declarations on variable declarations? For example:
public class xx {
public interface Foo<T> {
T getValue();
void setValue(T value);
}
public void resetFoos(Iterable<Foo<?>> foos) {
for (Foo<?> foo : foos) {
final <T> Foo<T> typedFoo = foo;
foo.s