官术网_书友最值得收藏!

Smart types checking with generic reified parameters

While implementing functions that support generic type arguments, we often deal with the need to provide additional information about object types at runtime. On the JVM platform, types have their representations in the Class<T> class instances. For example, we can face such a need while parsing JSON formatted data to the Kotlin class instances using the Gson library:

data class ApiResponse(val gifsWithPandas: List<ByteArray>)
data class Error(val message: String)

fun parseJsonResponse(json: String): ApiResponse {
Gson().fromJson(json, ApiResponse::class.java)
}

Normally, we can't access the generic type argument at runtime because of a JVM types erasure. However, Kotlin allows you to overcome this limitation because it preserves the type argument at runtime. In this recipe, we are going to tune up Gson's fromJson(json: String, Class<T>) function to get rid of the additional type argument.

主站蜘蛛池模板: 平遥县| 平远县| 丰都县| 万盛区| 保德县| 潢川县| 大化| 增城市| 巴南区| 郁南县| 尼木县| 青海省| 正定县| 山东| 泽库县| 四会市| 文昌市| 德阳市| 龙陵县| 六枝特区| 南涧| 白银市| 崇左市| 莱芜市| 女性| 高台县| 湘阴县| 邵武市| 濉溪县| 房产| 辰溪县| 都昌县| 灵台县| 肥城市| 晋州市| 金乡县| 基隆市| 青阳县| 玛多县| 启东市| 三穗县|