I'm trying to use java.util.Function object as an input to a library class.
Function<? extends MyEntity, List> mapper;
public MyLibraryClass(Function<? extends MyEntity,List> mapper) {
...
}
public void aMethod(ClassExtendsMyEntity e) {
mapper.apply(e);
}
The line mapper.apply(e) doesn't compile.
If I change to use ? super instead of ? extends, then the fail will be in the client using this library in the following code:
Function<ClassExtendsMyEntity, List> mapper = e -> e.getListObjects();
new MyLibraryClass(mapper);
Can anyone help explain why getting this issue and if there is a way to get this working?
The declaration
Function<? extends MyEntity,List> mappermeans:mapperexpects an argument of some typeXwhich is a subtype ofMyEntity. The problem is, it doesn't tell what type it is. And therefore the compiler can't verify if your call passing an instance of typeClassExtendsMyEntityis valid. After allXmight beSomeOtherClassExtendingMyEntity.In order to fix this just make the function type
Function<MyEntity,List>