Skip to content
Advertisement

Java returning Generic Type problem: unchecked overriding return type requires unchecked conversion

Hi I am having problems with Generic Types and warning that I get from IDE. I have class that holds generic type value:

public class Result <OUT>{
    private final OUT outputValue;
    
    public OUT getOutputValue() {
        return outputValue;
    }
}

I have abstract class:

public abstract class CustomSource {

      public abstract <T> SourceFunction<T> getSource();
}

and class that extends it:

public class OtherCustomSource extends CustomSource {

      @Override
      public SourceFunction<Result<MyEvent>> getSource() {
          ...some code...
      }
    }

IDE is giving me warning: unchecked overriding return type requires unchecked conversion. What I am missing?

Answer

public abstract <T> SourceFunction<T> getSource();

This is not the promise you intended to make. This says “for every T, I promise I can get a source of type SourceFunction<T>.” Then you came along and subclassed it with

public SourceFunction<Result<MyEvent>> getSource();

Which says “specifically, I can get you a source of type Result<MyEvent>“, a much weaker promise.

If you intend that getSource only return one specific type, your generic should be on the CustomSource class, not the getSource function.

public abstract class CustomSource<T> {
  public abstract SourceFunction<T> getSource();
}

public class OtherCustomSource extends CustomSource<Result<MyEvent>> {

  @Override
  public SourceFunction<Result<MyEvent>> getSource() {
      ...some code...
  }
}

Then it makes sense to use OtherCustomSource as a CustomSource<Result<MyEvent>> (since it can get a source of type Result<MyEvent>), but it makes no sense to treat a OtherCustomSource as a CustomSource<Integer>, for example.

Advertisement