- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 91字
- 2021-07-23 19:05:59
How it works...
We have implemented an extension function for the Gson type. Thanks to adding the reified modifier, we can access the generic type argument at runtime and pass it to the original fromGson() function.
As a result, we are able to use the more elegant version of the fromGson() function in our code:
data class ApiResponse(val gifsWithPandas: List<ByteArray>)
val response = Gson().fromJson<ApiResponse>(json)
We could also benefit from Kotlin smart casting and omit the explicit type declaration from the function call:
val response: ApiResponse = Gson().fromJson(json)