Search code examples
javagenericsinterfacecompiler-errors

Java Generic interface with List<T> not accepting object type


I am trying to implement a system as follows:

DtoMapper: This is an interface which defines a contract any third party mappers should return objects as

    public interface DtoMapper<T> {

    /**
     * Converts list of T into FooResponse
     * @param List of T
     * @return FooResponse
     */
    FooResponse convertToFooResponse(final List<T> rewards);

FooMapper: implements DtoMapper passing a List of Bar as method argument, however the compiler does not like my override of the method implementation and is wanting the second implementation (bottom).

public final class FooMapper implements DtoMapper {


    @Override
    FooResponse convertToFooResponse(final List<Bar> listOfBars) {
        ... Logic
    }

     @Override
    public convertToFooResponse(final List listOfBars) {
        ... I dont want this
    }

How can I make my interface work with this requirement, so that in future another implementation of say public convertToFooResponse(final list<Snafu> listOfSnafus); ?


Solution

  • You need to explicitely implement DtoMapper<Bar> instead of DtoMapper.

    Example:

    public interface DtoMapper<T> {
    
        /**
        * Converts list of T into FooResponse
        * @param List of T
        * @return FooResponse
        */
        FooResponse convertToFooResponse(final List<T> rewards);
    }
    
    public class FooMapperImplementation implements DtoMapper<Bar> {
        @Override
        public FooResponse convertToFooResponse(List<Bar> rewards) {
            return null;
        }
    }