I wrote a Java App where data was retrieved from an API in JSON. Depending on the endpoint the actual data could be very divers. So I made a function to convert the data to the required class for every possible class. This gives me multiple functions which only differ in the classtype to convert to. Following are two examples:
public List<ZermeloBranch> processBranches(ZermeloApiResponseObject responseObject) {
List<ZermeloBranch> branches = new ArrayList<>();
List<LinkedTreeMap> branchMaps = responseObject.getData();
Gson gson = new Gson();
for (LinkedTreeMap treeMap : branchMaps) {
branches.add(gson.fromJson(gson.toJsonTree(treeMap).toString(), ZermeloBranch.class));
}
return branches;
}
public List<ZermeloAnnouncement> processAnnouncements(ZermeloApiResponseObject responseObject) {
List<ZermeloAnnouncement> announcements = new ArrayList<ZermeloAnnouncement>();
List<LinkedTreeMap> announcementMaps = responseObject.getData();
Gson gson = new Gson();
for (LinkedTreeMap treeMap : announcementMaps) {
announcements.add(gson.fromJson(gson.toJsonTree(treeMap).toString(), ZermeloAnnouncement.class));
}
return announcements;
}
Now I am rewriting this app to Kotlin and I summise it should be possible to write one function to process the data passing the class to decode to as a parameter. So I made both ZermeloBranch and ZermeloAnnouncement inherit from ZermeloDataObject. I would like to write one function like this:
fun processDataToList(data:JSONArray, convertToClass:KClass<out ZermeloDataObject>):List<KClass<out ZermeloDataObject>>{
val returnList:ArrayList<KClass<out ZermeloDataObject>> = arrayListOf()
val gson = Gson()
for (item in 0 until data.length()){
returnList.add(gson.fromJson(item, convertToClass))
}
return returnList
}
and call it with processDataToList(data, ZermeloAnnouncements::class) and get a List<ZermeloAnnoucement> returned of call it with processDataToList(data, ZermeloBranch::class) and get a List<ZermeloBranch> returned.
Alas, the compiler gives me an error on gson.fromJson stating "None of the following functions can be called with the arguments supplied" and then it lists all possible functions.
Is it possible to use one function as I propose, and if so, what am I doing wrong?