https://kotlinlang.org logo
#feed
Title
# feed
t

trubesv

09/18/2017, 1:48 PM
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

kevinmost

09/18/2017, 1:50 PM
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

trubesv

09/18/2017, 1:54 PM
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

diesieben07

09/18/2017, 3:15 PM
You don't need to specify the type, because the compiler can infer it.
👍 1
t

trubesv

09/18/2017, 4:24 PM
Infer it meaning it determines it by "reading" the type of the function parameter?
d

diesieben07

09/18/2017, 7:27 PM
You could put it like that, yes.
t

trubesv

09/18/2017, 9:24 PM
Well, thanks for your input and explanations, it appreciated 🙂
a

arthur

09/18/2017, 10:20 PM
Thanks for this. I didn't know you could do this with reified generics
K 1
t

trubesv

09/18/2017, 10:24 PM
@kevinmost Fixed the line to
inline fun <reified T> Gson.getList(json: String): T? = fromJson<T>(json, object : TypeToken<T>() {}.type)
👌 1
k

kirillrakhman

09/19/2017, 11:39 AM
You could also think about caching the type token
t

trubesv

09/19/2017, 2:27 PM
Is this possible in a file where I grouped extensions? (no classes)
d

diesieben07

09/19/2017, 2:40 PM
You can use reified type parameters on any inline function, extension or not.
t

trubesv

09/19/2017, 3:02 PM
@diesieben07 I was asking about caching
TypeToken
, my guess is that I should
val
it but does it work outside a
class
?
d

diesieben07

09/19/2017, 3:03 PM
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

trubesv

09/19/2017, 3:23 PM
Ok I see now, thanks for the explanation 🙂
3 Views