Skip to content
Advertisement

Generics code not working when i try to return concrete object

The goal i am trying to achieve, is to have different FileLoaders like CSVFileLoader, ExcelFileLoader that can load up any object of type T, as long as it know how to convert using ‘C’ and create the object of type T. Hope this makes sense.

I am trying to use generics to create a generic FileLoader that will take a Converter of type C and return a List of Object of type T. So I went about creating something like the below but it inst working as expected.

I am getting an error while trying to return object Transaction in the convert method. How should I rewrite this so that it can use generics and I can improve this code to work. I understand there is type erasure, so that is why its complaning in the below code but not sure how to fix it. Please advise

JavaScript

So with the above interfaces, i tried implementing my classes but clearly I am going wrong, so my understanding isnt great and I would like some help as to where I am going wrong.

JavaScript

Advertisement

Answer

The source code in the question for TransactionConverter does not implement the interface Converter. Because it’s trying to implement it with the concrete type of Transaction, it should specify that in the implements clause and should not declare a type parameter for itself. It should use the concrete type of Transaction anywhere that T was used in Converter. Here’s the resulting source:

JavaScript

The type parameter C is not used in the FileLoader interface, so it is redundant. The fact that a converter is used is an implementation detail of CSVFileLoader in this code. Here’s the updated interface declaration:

JavaScript

If I understand your intent, CSVFileLoader should be able to work with any implementation of Converter, but it currently requires a TransactionConverter. It also uses the name transactions for the list of results, but these might not be Transaction objects if another type of Converter is used. Here’s the updated implementation:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement