<https://blog.simon-wirtz.de/kotlin-reified-types/...
# feed
t
Funny, I read this this morning in the subway K Helped me understand and write this dirty line:
inline fun <reified T> getList(json: String): T? = Gson().fromJson<T>(json, object : TypeToken<T>() {}.type)
(used to deserialize an ArrayList of custom objects)
k
is
getList
the name you want for that method?
val user = getList<User>(json)
doesn't seem right to me
👍 1
you might also want to have a cached instance of Gson so you're not making new ones for every deserialization
t
Actually I use it directly as a parameter so it looks like:
Copy code
fun newList() { /* create & populate a new list */ }
fun someFunction(list: ArrayList<SomeObject>) { ... }

someFunction(getList(json) ?: newList())
I don't clearly understand exactly why but I don't need to specify
<ArrayList<SomeObject>>
before the parenthesis somehow
Also, thanks for noticing the
Gson()
"error", I must have kept it after trying things and forgot to change it 🙂
d
You don't need to specify the type, because the compiler can infer it.
👍 1
t
Infer it meaning it determines it by "reading" the type of the function parameter?
d
You could put it like that, yes.
t
Well, thanks for your input and explanations, it appreciated 🙂
a
Thanks for this. I didn't know you could do this with reified generics
K 1
t
@kevinmost Fixed the line to
inline fun <reified T> Gson.getList(json: String): T? = fromJson<T>(json, object : TypeToken<T>() {}.type)
👌 1
k
You could also think about caching the type token
t
Is this possible in a file where I grouped extensions? (no classes)
d
You can use reified type parameters on any inline function, extension or not.
t
@diesieben07 I was asking about caching
TypeToken
, my guess is that I should
val
it but does it work outside a
class
?
d
You can't really cache the
TypeToken
, since you don't have anything to cache by (i.e. you don't have a key for the cache).
t
Ok I see now, thanks for the explanation 🙂