- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 143字
- 2021-07-23 19:05:58
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.
推薦閱讀
- Visual Basic .NET程序設計(第3版)
- Intel Galileo Essentials
- Microsoft Application Virtualization Cookbook
- Maven Build Customization
- 羅克韋爾ControlLogix系統應用技術
- C語言程序設計
- Spring Cloud、Nginx高并發核心編程
- 新編Premiere Pro CC從入門到精通
- Building a Recommendation Engine with Scala
- 嚴密系統設計:方法、趨勢與挑戰
- ExtJS高級程序設計
- 移動增值應用開發技術導論
- Unity Character Animation with Mecanim
- Advanced Python Programming
- 前端架構設計