When is it worthwhile to add a generic extension f...
# announcements
k
When is it worthwhile to add a generic extension function to an existing class? For example, I often use Google's Gson to deserialize JSON data, and since Gson is a Java library, I have
Copy code
Gson().fromJson(json, MyDataClass::class.java)
and I realize I could write
Copy code
inline fun <reified T> Gson.fromJson(json: String): T = this.fromJson(json, T::class.java)
That way I can reduce the above expression to
Copy code
Gson().fromJson<MyDataClass>(json)
My question is, is it worth doing that? Do I really gain anything? What do you think?
j
You would need to use
typeOf
or else things like List and Map and other generic types will be broken.
k
I don't think
typeOf<T>.javaClass
works, but the question is, should I be trying that at all? Should I just go with the two-arg version that takes a Java class, or is it worth it to try to add the extension function?
a
You would gain more readability in your code and the fact that you are directly inlining the function, means there is no extra overhead. So, no loss in performance However, as @jw said, If you have a generic class, i.e. you'll need extra work in your function. Is it worth or not? That is for you to decide. As for my unprofessional opinion, I think it is worth it
k
I switched to
fromJson(json, typeOf<T>().javaType)
and now I get a
NotImplementedError
(Java type is not yet supported for types created with createType) pointing to my data class, which I don't understand yet, but I'm still not sure this is a good idea in the first place
Hmm. I'm using this for JSON decomposition, so the only lists or maps I have contain explicit data types, and my sample works. Thanks for the feedback, though