0

I am trying to make a function that returns a T/Any object. The only thing is that i am not quite sure how to do it.

 fun readMockData(context: Context, filename: String): Any {
    val json = context.assets.open("$filename.json").bufferedReader().use(BufferedReader::readText)
    return RetrofitSingleton.GSON.fromJson(json, object : TypeToken<Any>() {}.type)
}

This is what i tried at first, but i am getting an error. How am i supposed to make this function properly?

3
  • <T> and Any are not the same thing. What exactly are you trying to achieve? Commented Jun 11, 2021 at 9:20
  • i try to return a generic object that i just can cast to whatever object i need. Commented Jun 11, 2021 at 9:23
  • i get a object from this json, turns it to the right object and return it normally. But i make the same function that look so similar so many times, so i wondered if i could make something more generic? if that makes sense Commented Jun 11, 2021 at 9:25

1 Answer 1

2

If I understand your problem correctly, this is what you need:

@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T> readMockData(context: Context, filename: String): T {
    val json = context.assets.open("$filename.json").bufferedReader().use(BufferedReader::readText)
    return RetrofitSingleton.GSON.fromJson(json, typeOf<T>().javaType)
}

Note it has to be inline, because otherwise there is no way to acquire a type. If your function is longer than above, it may be a good idea to split it into an inline reified wrapper and the main function that accepts Type as a parameter.

It uses reflection, so you need to add a dependency to it. Also, typeOf() is experimental, but from my experience it just works (at least on JVM) and it is there for a long time, so I guess it won't change.

Sign up to request clarification or add additional context in comments.

1 Comment

In the meantime I noticed I probably missed .javaType in my original answer. I edited it, but please confirm if you needed to add it, so the answer will be the correct one (for future readers). @Meyben

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.