0

I have an interface called IUploader<T> which has many abstract methods. One of them is List<UploadErrors> getErrors() method. The behaviour is given below.

interface IUploader<T> {
    T parse();
    // some more abstract and default methods
    List<UploadErrors> getErrors();
}
void someMethod(IUploader uploader) {
    // calling other methods of IUploader implementations
    List errors = uploader.getErrors(); // Problem - Getting List without type parameter
}
<T> void someMethod(IUploader<T> uploader) {
    // calling other methods of IUploader implementations
    List<UploadErrors> errors = uploader.getErrors(); // Works fine
}

The problem here is, when I give type parameter for IUploader in someMethod(), I'm getting the local variable of getErrors() method as List<UploadErrors>. But without type parameter, I'm getting simply List. There is no relation between <T> and UploadErrors, but why this behaviour? The reason I have added Intellij IDEA is because, when I do Alt+Enter to "Introduce local variable", I get this two types. I have not tried in other IDEs. Please help me to understand this behaviour.

the_tech_maddy
  • 575
  • 2
  • 6
  • 21
  • Using raw types erases _all generics_ related to the type. – Slaw Oct 31 '19 at 03:00
  • @Slaw yes. But `UploadErrors` is not related to type `T`. Totally different – the_tech_maddy Oct 31 '19 at 03:07
  • But it's related to the type `IUploader` and using a raw `IUploader` erases _all generics_ related to `IUploader`. And since `List` is using generics and is a return type of a method enclosed by `IUploader` it gets erased to `List` when using a raw `IUploader`. – Slaw Oct 31 '19 at 03:15
  • When you use a raw type you're essentially using pre-generics code. In other words, in the context of the raw type generics may as well not exist. – Slaw Oct 31 '19 at 03:22
  • Ok, I'm getting it now. So, I should always use generic type, If it has type parameter to not lose the genericity at anywhere – the_tech_maddy Oct 31 '19 at 03:25
  • Yes, unless dealing with legacy code you should virtually never use raw types. – Slaw Oct 31 '19 at 03:33

0 Answers0