I’m having trouble understanding the finer points of Java generics with wildcards. specifically, why doesn’t this compile.
public class Test {
abstract class Function<A, B> {
abstract B call(A a);
}
interface PropertyType {
String bubbles();
}
class Apartment implements PropertyType {
@Override
public String bubbles() {
return "bubbles";
}
}
public void invokeFunctionOnAList() {
List<Apartment> apts = new ArrayList<Apartment>();
functionLoop(apts, new Function<Apartment, String>() {
@Override
String call(Apartment a) {
return a.bubbles();
}
});
}
public void functionLoop(List<? extends PropertyType> list, Function<? extends PropertyType, String> t) {
for (PropertyType p : list) {
t.call(p);
}
}
}
Your compiler does not know if you are using same type in List and Function. Therefore you have to tell him this.
Try this: