inline函数

inline内联函数,最终编译时是要编译到调用它的代码块中,这时候T的类型实际上是确定的,因而Kotlin通过reified这个关键字告诉编译器,T这个参数可不只是个摆设,我要把它当实际类型来用呢。

  1. inline fun <reified T: Any> Gson.fromJson(json: String): T{
  2. return fromJson(json, T::class.java)
  3. }
  4. interface Api {
  5. fun getSingerFromJson(json: String): BaseResult<Singer>
  6. }
  7. object ApiFactory {
  8. val api: Api by lazy {
  9. Proxy.newProxyInstance(ApiFactory.javaClass.classLoader, arrayOf(Api::class.java)) {
  10. proxy, method, args ->
  11. val responseType = method.genericReturnType
  12. val adapter = Gson().getAdapter(TypeToken.get(responseType))
  13. adapter.fromJson(args[0].toString())
  14. } as Api
  15. }
  16. }
  17. fun main(args: Array<String>) {
  18. val json = File("result_singer_field_loss.json").readText()
  19. val result : BaseResult<Singer> = ApiFactory.api.getSingerFromJson(json)
  20. println(result.content.name.isEmpty())
  21. }
  1. package com.benny.utils
  2. import android.util.Log
  3. inline fun <reified T> T.debug(log: Any){
  4. Log.d(T::class.simpleName, log.toString())
  5. }
  6. debug(whatever)